Java classes and objects


In Java, classes and objects are key concepts of object-oriented programming. A class is a blueprint or a template that defines the properties and behaviors of objects, while an object is an instance of a class that has its own state and behavior. Here’s an example of a class and an object in Java:

// Defining a class
public class MyClass {

    // Instance variables
    private String name;
    private int age;

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

    // Getter methods
    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    // Setter methods
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    // Instance method
    public void printDetails() {
        System.out.println("Name: " + this.name);
        System.out.println("Age: " + this.age);
    }
}

In this example, MyClass is a class that defines two instance variables (name and age), a constructor that initializes these variables, getter and setter methods that allow you to get and set the values of the variables, and an instance method (printDetails) that prints the details of the object.

Now, let’s create an object of the MyClass class:

// Creating an object
MyClass obj = new MyClass("John", 30);

// Accessing instance variables
String name = obj.getName();
int age = obj.getAge();

// Calling instance method
obj.printDetails();

In this example, we create an object of the MyClass class by using the new keyword and passing two arguments to the constructor. We then access the instance variables by calling the getter methods and storing them in local variables. Finally, we call the printDetails method on the object to print its details.

In summary, a class in Java is a blueprint that defines the properties and behaviors of objects, while an object is an instance of a class that has its own state and behavior. To use a class, you need to create an object of the class and access its properties and methods using dot notation. Understanding classes and objects are essential to writing object-oriented programs in Java.

A quick recap of Java