Java Object and Classes

java

In Java, an object is an instance of a class. A class is a blueprint or template that defines the attributes and behavior of an object.

For example, consider the following class definition:

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 void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

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

This class defines a Person object with two attributes: name and age. It also defines four methods: a constructor method to create a Person object, and getter and setter methods for the name and age attributes.

To create an object of this class, you can use the new operator and call the constructor method:

Person person = new Person("John", 30);

This will create a new Person object with the name “John” and age 30. You can then use the object’s methods to get and set the values of the attributes:

String name = person.getName(); // Returns "John"
int age = person.getAge(); // Returns 30
person.setName("Jane");
person.setAge(25);