Object in Java

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables like the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword in Java Programming language.

A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.

  • I found various Object Definitions:

  • An object is a real-world entity.

  • An object is a runtime entity.

  • The object is an entity which has state and behavior.

  • The object is an instance of a class.

Real-world examples

Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Chair, Bike, Marker, Pen, Table, Car, Book, Apple, Bag etc. It can be physical or logical (tangible and intangible).

How to Declare, Create and Initialize an Object in Java

A class is a blueprint for Object, you can create an object from a class. Let's take Student class and try to create Java object for it. Let's create a simple Student class which has name and college fields. Let's write a program to create declare, create and initialize a Student object in Java.

public class Student {
  private String name;
  private String college;
  public Student(String name, String college) {
    super();
    this.name = name;
    this.college = college;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getCollege() {
    return college;
  }
  public void setCollege(String college) {
    this.college = college;
  }
  public static void main(String[] args) {
    Student student1 = new Student("Suresh", "PMT");
    Student student2 = new Student("Rakesh", "NET");
    Student student3 = new Student("Dev", "DDI");
  }
}​

From the above program, the Student objects are:

Student student1 = new Student("Suresh", "PMT");
Student student2 = new Student("Rakesh", "NET");
Student student3 = new Student("Dev", "DDI");

Each of these statements has three parts (discussed in detail below):

Declaration: The code Student student; declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.