What is object in java

In Java, an object is an instance of a class. A class is a blueprint or template for creating objects, and an object is a specific instance of that blueprint.

Objects in Java have state and behavior. The state of an object is represented by its attributes, also known as fields or instance variables. The behavior of an object is represented by its methods, which define the actions that can be performed on the object.

Here’s an example of an object in Java:

public class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 30

        person1.setAge(31);
        System.out.println(person1.getAge()); // output: 31
    }
}

In this example, we have defined a Person class with fields for name and age, and methods for getting and setting those fields. We then create a new Person object called person1 and set its name and age fields. We can then use the getName() and getAge() methods to get the values of these fields, and the setAge() method to update the age field.

Share