Can any one tell me the difference between these two object creation
Method 1 :
Superclass ob = new Childclass();
Method 2 :
Childclass ob = new Shildclass();
What will be the difference between both objects and why.
Thanks, Vijesh
Can any one tell me the difference between these two object creation
Method 1 :
Superclass ob = new Childclass();
Method 2 :
Childclass ob = new Shildclass();
What will be the difference between both objects and why.
Thanks, Vijesh
The difference is:
Superclass a = new ChildClass();
is declared as a type Superclass instance, meaning it's limited to the members of the Superclass.
ChildClass c = new ChildClass();
is of type ChildClass and has access to all the members of both the ChildClass, and those inherited from Superclass.
The object creations are the same. In both cases you are creating an instance of the Childclass
.
The difference between those two snippets is in what you do with the object references after the object creation.
By assigning the object reference to a variable of type Superclass
you are temporarily "hiding" some aspects of the Childclass
-ness of the object. But the object remains an instance of Childclass
, as illustrated by this:
Superclass ob = new Childclass();
System.out.println(ob.getClass()); // prints "Childclass"