TAGS :Viewed: 17 - Published at: a few seconds ago

[ Difference between an Instance and Object in Java ]

In Java, what is the difference between instance of a class and Object of a class.

For a class A, Take a look :

line 1 : A a; // Declaring a reference variable of class A

Line 2 : a = new A();// Instantiating an object of class A

So....can the line 2 also be : // Instantiating an instance of class A

which mean Instance and Object are absolutely the same thing ?

Please give an objective answer than subjective.

Answer 1

Line 1 declares a variable, it doesn't reference anything, though, its value is null.

Line 2 creates a new object and assigns it to the variable a.

An object is an instance of a class. A class is something used to create objects, an object is something created (instantiated) using that class as a template.

"instance" means a specific occurrence of something. For instance, you could talk about database instances, where each instance is an installation in a specific place on a specific server somewhere. Likewise with objects, an instance is a specific member of a category.

Answer 2

The term "instance of" is used to show you from which classes the specific object origins from. The objects Buddy, Lucky and Sparky are instances of dogs but also instances of animals. So the object itself can be an instance of multiple classes. A cat is also an instance of animals and an instance of cats but not an instance of dogs.

public abstract class Animals{...}

public class Dogs extends Animals{...}

public class Cats extends Animals{...}

Answer 3

The object and the instance are of different stories. It's like asking what is the difference between a Car and an Engine.

Anyway, an object is a representation of a class. A class is the file that you write and save.

Once you use a class and put it into memory, an object is created.

Instantiating is the process of using a class to create an object based on that class and putting it into memory.

A a;  // Declaring a reference variable of class A

This means you are reserving a variable for a particular object or particular class.

a = new A();// Instantiating an object of class A

This means that you are using the A.class as your base class to create the object a. And this process is basically Instantiation.

Answer 4

Line 1, you declare an variable which type is A, but the variable doesn't have any value, its value is null.

In Line2, you created an object of Class A using new, and assign a reference of that object to variable a, in another words, you assigned a reference of A class's object to the variable a.

a is called the instance of class A, the object it refers to is called the object of A