What is the difference between object and reference in java?

Java 8Object Oriented ProgrammingProgramming

A class in a blue print/user defined datatype in java that describes the behavior/state that the object of its type support.

Example

public class Student {
   String name "Krishna";
   int age = 20;
   void greet() {
      System.out.println("Hello how are you");
   }
}

An object is an instance of a class created from it using the new keyword. Once you create an object of a class, using it you can access he members of the class. In the below given code an object of the class Student is created.

public class Example {
   public static void main(String args[]) {
      Student obj = new Student();
   }
}

Classes, interfaces, arrays, enumerations and, annotations are the in Java are reference types in Java. Reference variables hold the objects/values of reference types in Java

difference between object and reference

When you create an object of a class as −

Student obj = new Student();

The objects are created in the heap area and, the reference obj just points out to the object of the Student class in the heap, i.e. it just holds the memory address of the object (in the heap).

And since the String is also an object, under name, a reference points out to the actual String value (“Krishna”).

In short, object is an instance of a class and reference (variable) points out to the object created in the heap area.

raja
Published on 05-Jul-2019 08:22:48
Advertisements