• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Difference between instantiating and creating an object

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
reply
    Bookmark Topic Watch Topic
  • New Topic