Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between instantiating and creating an object

 
Praveen palukuri
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
would u please tell me the difference between the following:

Class Test1{....}
Class Test2
{
Test1 t1;
Test1 t1 = new Test1();
}
what is the difference between above 2 statements?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, "instantiating an object" and "creating an object" is the same thing. Different words with the same meaning.

About your statements; do you mean the difference between these two?

Test1 t1;
Test1 t1 = new Test1();

In the first line, you declare a variable t1 of type Test1. You are not initializing it, and you are not instantiating/creating an object. Because it's a member variable (of class Test2), it will get the default value null.

In the second line, you declare a variable t1 of type Test1 and you instantiate/create a new Test1 object, and you initialize the variable t1 with this object (i.e. t1 is a reference to the newly created object).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first statement is only declaring a reference. As it is a field, it will get assigned the default value of null. No object gets created.

The second statement is declaring a reference, creating (=instanciating) an object via new, and letting the reference reference that object (using the assignment operator).

Does that help?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic