Object Definition in Java

Objects are key to understanding object-oriented technology. The purpose of the object-oriented programming is to implement the real word entities in programming. It also emphasis on the binding of data. There are various OOPs concepts among them Object is one of them. In this section, we will discuss the object definition in Java.

Object Definition

In object-oriented programming terminology, an object is a member of Java class. It is also known as instance of the class. Note that objects are created at run time. In simple words, object is a real word entity. For example, dog, car, pen, desk, etc. Each object shares the following two characteristics:

  • Identity:Object identity is a unique ID. The value of the ID is not visible to the external user. It is used internally by the JVM to identify each object uniquely.
  • State: The state of an object stored in variables (fields).
  • Behavior: The methods shows the behavior of an object.

Example of an Object

Let's take an example of dog. The state of dog includes, color, hungry, gender, breed, and age. The dog behavior includes running, barking, eating, sleeping, wagging tail, fetching, etc.

How to Create a Java Object?

There are the following three steps to create an object from a class.

  • Declaration
  • Instantiation
  • Initialization

Declaration: A variable declaration with a variable name with an object type.

Instantiation: Java provides the new keyword to create an object of the class.

Initialization: The new keyword is followed by a call to a constructor. The call initializes a new object. There are the following three ways to initialize an object in Java:

  • By reference variable: It means storing data into an object. Multiple objects can be created and store information in it through reference variable.
  • By method: Initializing the objects by invoking the methods.
  • By constructor: Constructors can also be used to create an object.

Different Ways to Create an Object in Java

There are various ways to create an object in Java:

  • Using new keyword
  • Using newInsatnce() Method
  • Using clone() Method
  • Using Deserialization
  • Using Factory method

Anonymous Object

Java allows us to create an anonymous object. It means, we can create an object without name. Therefore, we can say that an object that has no reference is known as anonymous object. The disadvantage of an anonymous object is that it can be used at the time of object creation only. It is good to use an anonymous object if we want to use object once.

For example:

Calling method through anonymous object.

We can also create multiple object of a type in a line:

Using Object in a Java Program

Student.java

Output:

Student Id: 105
Student Name: Nitin