-3

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

Michael_Scharf
  • 31,056
  • 20
  • 68
  • 89
V I J E S H
  • 7,184
  • 10
  • 28
  • 37

3 Answers3

1

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.

Stultuske
  • 8,840
  • 1
  • 22
  • 34
0

From Difference Between Static Binding And Dynamic Binding In Java

First one called Dynamic binding is a which happens during run time. It is also called late binding because binding happens when program actually is running.

During run time actual objects are used for binding. For example, for “a1.method()” call in the below picture, method() of actual object to which ‘a1’ is pointing will be called. For a2.method() call, method() of actual object to which ‘a2’ is pointing will be called. This type of binding is called dynamic binding.

The dynamic binding of above example can be demonstrated like below. enter image description here

Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
0

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"
Stephen C
  • 669,072
  • 92
  • 771
  • 1,162