What is Object in Java (with Examples)

In this tutorial, we will learn about what is object in Java with the help of realtime examples.

An object in Java is a named entity that encapsulates state (attributes) and behavior (methods). In other words, a real-world entiry that has state and behavior is called object. It is a basic element of an object-oriented programing system.

An object consists of related data and instructions for performing actions on that data. Here, the state represents properties and behavior represents actions. The best way to define an object is, what you see around you in real-life are all objects. Book, pen, pencil, TV, fridge, washing machine, mobile phone, etc. are all examples of objects.

An object is an instance of a class. Each instance of an object holds its own relevant data.

Learn object in Java.

Key Characteristics of Object in Java

An object has three characteristics in Java that are as follows:

  1. State: A state represents the properties or attributes of an object, which are defined using instance variables. The state of an object is essential because the outcome of its methods (functions) often depends on these properties. For example, a Car object may have attributes like color, make, and speed that define its state.
  2. Behavior: Behavior represents the functionality or actions an object which are defined using methods in Java. For instance, a Car object may exhibit behaviors such as start(), stop(), and accelerate().
  3. Identity: Identity refers to the unique reference or memory address of an object in Java. It differentiates one object from another, even if they have the same state or attribute values. This identity is represented internally by the reference of an object. The unique identity allows Java to differentiate between two objects in memory.

Let us consider some real-life examples to understand about objects in Java.

Real-life Examples of Object in Java

In Java, we can take a real-world object “Person”. A person has three primary characteristics:

  • Identity: Name is the unique identifier of any person.
    • Example: String name = “John”;
  • State (Properties): The attributes that define the physical properties of the person. For example, hair color, eye color, height, etc. We can define these properties in Java like this:
    • String hairColor = “black”;
    • String eyeColor = “black”;
    • double height = 5.9;
  • Behavior (Actions): The actions or functionalities that a person can perform are eating, sleeping, walking, playing, studying, etc. We can represent these actions in Java as methods like this:
    • eat()
    • sleep()
    • walk()
    • play()
    • study()

In this way, when you combine state (properties) and behavior (actions) together of any real-world object, it makes an object in Java.

Let’s take another simple real-life example “Pencil” as an object.

  • Identity: The unique identifier or name of the pencil, such as Natraj.
  • State (Properties): The properties, such as color, length, material, etc. of a pencil are black, 7 inches, and wood, respectively.
  • Behavior (Actions): The actions of the pencil can be writing, drawing, etc.

Creating an Object in Java

Everything is an object in Java. A class is a model or user-defined template or blueprint that defines the structure and behavior of objects. It combines the relevant data members and methods (behaviors) that an object of that class will have.

Creating an object in Java means instantiating the class, which allocates memory for storing the object’s attributes and methods temporarily during program execution. In simple words, we create an object of a class to store data temporarily. By creating an object, we can access members of any class.

To create an object in Java, you use the new keyword along with a class constructor. The general syntax for creating an object of a class in Java is as follows:

ClassName object_reference_variable = new ClassName();

For example:

School mySchool = new School();

In the above creation of an object,

  • School is the name of the class.
  • mySchool is an object reference variable which stores the address of the object in the stack memory.
  • new is a keyword in Java that stores the object in the heap memory.
  • School() represents the constructor of the class.
  • The equal sign (=) is an assignment operator that is used to assign the object created using new keyword to the object reference variable.

Example 1: Let’s write a Java program in which we will create an object of a class and access members of class using object reference variable.

package myProgram;
// Create a class named Person.
public class Person {
// Declare instance variables and assign values to it.	
String name = "John";
int age = 18;
// Declare an instance method.
void display() {
	System.out.println("Name: " +name);
	System.out.println("Age: " +age);
}
// Main method to start execution of Java program.
public static void main(String[] args) {
// Create an object of class Person.
   Person p = new Person();
// Call the method using object reference variable to display output.
   p.display();
	}
}
Output:
    Name: John
    Age: 18

Example 2:

package myProgram;
// Create a class named Person.
public class Person {
// Declare instance variables.	
String name;
int age;
// Declare a constructor with the same name as class.
Person(String name, int age){
  this.name = name;
  this.age = age;
}
// Declare an instance method.
void display() {
	System.out.println("Name: " +name);
	System.out.println("Age: " +age);
}
public static void main(String[] args) {
// Create an object of class Person.
   Person p = new Person("Alice", 25);
// Call the method using object reference variable to display output.
   p.display();
	}
}
Output:
     Name: Alice
     Age: 25

How to Create Multiple Objects in Java

You can also create more than one object of a single class. You can create multiple objects of one type like this:

Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();

The reference variables of all three objects will have different memory addresses. Let’s take an example on it.

Example 3:

package myProgram;
// Create a class named Hello.
public class Hello {
// Declare an instance variable of String type.
String name;
// Declare a constructor.
Hello(String name){
	this.name = name;
}
// Declare an instance method.
void showMe() {
	System.out.println("Hello, "+name);
}
public static void main(String[] args) {
// Create multiple objects of the same class Hello.
   Hello h1 = new Hello("John");
   Hello h2 = new Hello("Alice");
   Hello h3 = new Hello("Bob");

// Call the method using object reference variable to display output.
   h1.showMe();
   h2.showMe();
   h3.showMe();
	}
}
Output:
     Hello, John
     Hello, Alice
     Hello, Bob

Example 4:

package myProgram;
public class Pencil {
// Properties (States)
   String name;
   String color;
   double length;

// Constructor to initialize the pencil
   Pencil(String name, String color, double length) {
       this.name = name;
       this.color = color;
       this.length = length;
   }
// Methods (Behaviors)
   void write() {
      System.out.println(name + " is writing.");
   }
   void draw() {
      System.out.println(name + " is drawing.");
   }
public static void main(String[] args) {
// Creating a pencil object.
   Pencil pencil = new Pencil("Natraj", "Black", 7.0);

// Accessing properties
   System.out.println("Pencil Name: " + pencil.name);
   System.out.println("Pencil Color: " + pencil.color);

// Calling methods
   pencil.write();
   pencil.draw();
  }
}
Output:
     Pencil Name: Natraj
     Pencil Color: Black
     Natraj is writing.
     Natraj is drawing.

Hash Code Number in Java

When you create an object of a class in Java programming, memory is allocated in the heap area to store the instance variables (attributes) of that object.

Once the object is created, JVM generates a unique reference number (known as hash code) for the object, which acts as an identifier for the object during the program execution. This reference number helps the JVM to locate the object in the memory.

Note: For immutable objects like String, hash codes are not unique across objects with identical content.

The object reference variable stores this reference (also called address) in the stack memory. Object class in Java provides hashCode() method that returns the hash code number of an object. You can override it in custom classes to provide a specific implementation.

Example 5: Let’s write a Java program to get the hash code number of an object.

package myProgram;
public class Pencil {
    String name = "Natraj";
    String color ="Black";

public static void main(String[] args) {
// Creating a pencil object.
   Pencil pencil1 = new Pencil();

// Call hashCode() method of Object class to print the hash code of object.
   System.out.println("Hash code of object: " + pencil1.hashCode());
    }
}
Output:
    Hash code of object: 1579572132

The output shows the hash code of the object, which is a unique number generated by the JVM for this specific object.

What is Object Reference in Java?

An object reference is a unique identifier that is a hexadecimal number to represent the memory address of an object stored in the heap. Java does not allow direct access to an object’s memory address. Therefore, the reference acts as a “pointer” to locate and access the object.
The main purpose of object reference in Java is to:

  • Access the attributes (fields) of an object.
  • Invoke the methods (behaviors) associated with an object.

How are Object References Created in Java?

When you create an object of a class using the new keyword, the JVM:

  • Allocates memory for the object in the heap.
  • Generates a unique reference (called memory address) for the object.
  • Stores this reference in the object reference variable.

Note that every object in Java has a unique reference (memory address) unless it is explicitly designed to share data. Even if two objects have the same state (attributes), their references will be different.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *