Java Basics: Mastering Classes and Objects for Beginners

Java Basics: Class & Object
{getToc} $title={Table of Contents} $count={true}

Java Basics: Class & Object

Introduction to Java Class & Object

In Java, a class is the blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that an object of that class will have. An object, on the other hand, is an instance of a class. Objects represent real-world entities such as cars, animals, or even abstract concepts like bank accounts.

For example, if you think of a car as an object, its attributes might include brand, color, and model, while its behaviors could be driving, braking, or honking.


// Example of a simple class and object creation
class Car {
    String brand;
    String color;

    void displayInfo() {
        System.out.println("Brand: " + brand + ", Color: " + color);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Car class
        Car myCar = new Car();
        myCar.brand = "Toyota";
        myCar.color = "Red";
        myCar.displayInfo(); // Output: Brand: Toyota, Color: Red
    }
}

            

Explanation: In this example, we define a Car class with two attributes: brand and color. The displayInfo method prints these attributes. In the Main class, we create an object of the Car class using the new keyword and assign values to its attributes. Finally, we call the displayInfo method to print the details of the car.

Class Structure

A class in Java consists of three main components:

  • Fields (Variables): These are used to store the state or data of the class. For example, in a Person class, fields could include name and age.
  • Methods: These define the behavior or actions that the object can perform. For example, a Person class might have a method called introduce() to introduce themselves.
  • Constructors: These are special methods used to initialize the object's state when it is created.

class Person {
    // Fields
    String name;
    int age;

    // Constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method
    void introduce() {
        System.out.println("Hi, I am " + name + " and I am " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Person class
        Person person = new Person("Alice", 25);
        person.introduce(); // Output: Hi, I am Alice and I am 25 years old.
    }
}

            

Explanation: Here, the Person class has two fields: name and age. The constructor initializes these fields when a new Person object is created. The introduce method prints out the person's name and age. In the Main class, we create a Person object named Alice and call the introduce method to display her information.

Constructor

A constructor is a special method used to initialize an object. If no constructor is defined, Java provides a default constructor. Constructors can be overloaded, meaning you can have multiple constructors with different parameters.


class Dog {
    String breed;

    // Parameterized Constructor
    Dog(String breed) {
        this.breed = breed;
    }

    void bark() {
        System.out.println(breed + " is barking!");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object using the parameterized constructor
        Dog myDog = new Dog("Labrador");
        myDog.bark(); // Output: Labrador is barking!
    }
}

            

Explanation: In this example, the Dog class has a parameterized constructor that takes a breed as an argument and assigns it to the breed field. The bark method prints out the breed of the dog along with a message. When we create a Dog object with the breed "Labrador," the constructor initializes the object, and the bark method outputs the expected result.

this & this()

The this keyword refers to the current object, while this() is used to call one constructor from another within the same class. This is useful for reducing code duplication when you have multiple constructors.


class Rectangle {
    int length;
    int width;

    // Default Constructor
    Rectangle() {
        this(10, 5); // Calls parameterized constructor
    }

    // Parameterized Constructor
    Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    void displayArea() {
        System.out.println("Area: " + (length * width));
    }
}

public class Main {
    public static void main(String[] args) {
        // Using the default constructor
        Rectangle rect1 = new Rectangle();
        rect1.displayArea(); // Output: Area: 50

        // Using the parameterized constructor
        Rectangle rect2 = new Rectangle(20, 10);
        rect2.displayArea(); // Output: Area: 200
    }
}

            

Explanation: In this example, the Rectangle class has two constructors: a default constructor and a parameterized constructor. The default constructor calls the parameterized constructor using this(10, 5), which sets the default dimensions of the rectangle. The displayArea method calculates and prints the area of the rectangle. We create two Rectangle objects: one using the default constructor and the other using the parameterized constructor.

Object Creation

Objects are created using the new keyword followed by a constructor call. The new keyword allocates memory for the object and initializes it using the specified constructor.


class Laptop {
    String model;

    // Constructor
    Laptop(String model) {
        this.model = model;
    }

    void showModel() {
        System.out.println("Laptop Model: " + model);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object using the constructor
        Laptop laptop = new Laptop("MacBook Pro");
        laptop.showModel(); // Output: Laptop Model: MacBook Pro
    }
}

            

Explanation: In this example, the Laptop class has a constructor that initializes the model field. The showModel method prints out the model of the laptop. When we create a Laptop object with the model "MacBook Pro," the constructor initializes the object, and the showModel method displays the model name.

Nested Class

A nested class is a class defined inside another class. Nested classes can be either static or non-static. Static nested classes are associated with the outer class, while non-static nested classes (inner classes) are associated with an instance of the outer class.


class OuterClass {
    static class NestedClass {
        void display() {
            System.out.println("This is a nested class.");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of the nested class
        OuterClass.NestedClass nested = new OuterClass.NestedClass();
        nested.display(); // Output: This is a nested class.
    }
}

            

Explanation: In this example, the OuterClass contains a static nested class called NestedClass. Since the nested class is static, it can be instantiated without creating an instance of the outer class. We create an object of the NestedClass and call its display method to print a message.

Anonymous Inner Class

An anonymous inner class is a class without a name, often used for implementing interfaces or extending classes on the fly. Anonymous inner classes are useful when you need to override methods of an interface or a class without creating a separate named class.


interface Greeting {
    void sayHello();
}

public class Main {
    public static void main(String[] args) {
        // Creating an anonymous inner class that implements the Greeting interface
        Greeting greeting = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("Hello from Anonymous Inner Class!");
            }
        };
        greeting.sayHello(); // Output: Hello from Anonymous Inner Class!
    }
}

            

Explanation: In this example, we define an interface Greeting with a single method sayHello. Instead of creating a separate class to implement this interface, we use an anonymous inner class to provide the implementation directly in the Main class. The sayHello method is overridden to print a custom message.

Conclusion

Understanding classes and objects is fundamental to mastering Java programming. Classes provide structure, while objects bring them to life. Concepts like constructors, this, nested classes, and anonymous inner classes enhance flexibility and reusability in your code. Practice these concepts to build robust and maintainable applications.

By mastering the basics of classes and objects, you lay a strong foundation for more advanced topics in Java, such as inheritance, polymorphism, and design patterns. Keep experimenting with different examples to deepen your understanding!

Previous Post Next Post