Sumithra
Sumithra

Reputation: 6717

which is object and which is reference variable

Dog d=new Dog();

In the above line which is object and which is reference variable? or Whether object and reference variable are the same?

Upvotes: 2

Views: 224

Answers (3)

hvgotcodes
hvgotcodes

Reputation: 120318

d is a reference to a Dog object instance.

Object instances and references are not the same; references point to object instances.

To illustrate, you can do

 Dog d2 = d;

now you have 2 references, d and d2, that point to the same underlying instance of Dog.

Now if you do

d = new Dog();

d2 points to the first dog you created, and d points to the second (where it originally pointed to the first.) This statement creates a new object instance, and assigns it to the original Dog reference.

Upvotes: 6

Pops
Pops

Reputation: 30868

This seems like an easy question on the surface, but it's possible to get pretty involved in the semantics of what variables and objects actually are.

Sun, the company that invented Java, has a nice intro to the concept of Java variables here; it's part of a great beginner-level series called The JavaTM Tutorials. In your example, the variable is d, because that's the thing you'll use to refer to the useful stuff — i.e. the object — later on. In other words, d will refer to the object.

So, since d is the reference, new Dog() must be the object, right? Not quite. You don't really have an object anywhere in your line of code. Actually, you never really "see" objects in the code, because objects are just abstract concepts (again, I point you to the Java Tutorials page; objects are closely related to classes, but that's beginning to be a separate topic. All new Dog() does is tell the computer to run a constructor, which is like a special method that creates an object.

Once the computer creates the object, it sees the equal sign and makes d the "nametag" for that object. d and the object are not the same thing; d is more like an arrow that points at the object for the moment. You could say Dog d2 = d; on the next line and have two "nametags" for the same object. Alternatively, you could say d = new Dog(); again, and the old name d would be pointing to the new object. The old object would still exist, but it wouldn't have a "nametag," so you wouldn't be able to use it anymore.

I've intentionally oversimplified some things here to try to make the variable/object difference more clear. Please leave a comment if something is unclear to you.

Upvotes: 0

kasgoku
kasgoku

Reputation: 5027

new Dog();

The above statement creates an object in the heap which is an instance of the Dog class. If the above statement was by itself(i.e. without the "Dog d=" part), the new object will be lost to you as there won't be any way to access or "get to" it. d refers to the newly created object. You can use that reference to manipulate the new object.

Upvotes: 0

Related Questions