Reputation: 834
I really want to understand as what is the real time use of these :
1.What is the use of a Java concept-"Super class variable can reference a sub class object"? Even though by doing this the the SuperClass variable can only be used to access those parts of the object defined by the SuperClass but can't access subclass members.Which can even be achieved by the subclass object.
2.what is the need for dynamic method dispatch ? I have an example below :
class A
{
void disp()
{
System.out.println("in A");
}
}
class B extends A
{
void disp()
{
System.out.println("in B");
}
}
class C extends A
{
void disp()
{
System.out.println("in C");
}
}
public class mainclass
{
public static void main(String[] args)
{
A a= new A();
B b=new B();
C c=new C();
A ref;
ref=b;
ref.disp();//calls class B method
ref=c;
ref.disp();//calls class C method
ref=a;
ref.disp();//calls class A method
}
}
This above code uses dynamic method dispatch by assigning the different child class object to the super class reference variable. My question is why to use "ref" and assign objects to it and then call the functions?We can call the subclass function even without using this "ref" and object assignment(Dynamic dispatch).
we can call like this also :
a.disp();//calls A method
b.disp();//calls B method and so on.
c.disp();
Could anyone please help me understand the real time use of these two concepts?
Thanks in advance.
Upvotes: 0
Views: 1722
Reputation: 49432
Runtime polymorphism is a way to implement Coding to Interface, rather than implementation!
Polymorphism is like declaring an uniform interface , leaving implementation details to concrete types that implement the interface. It is like defining a contract binding to all who implements the interface . This enable objects to interact with one another without knowing their exact type.
Let us assume you have a method (trivial example) :
public boolean remove(List list) {
return list.remove();
}
Since you have defined the argument of type List
interface , it is open to take any object of implementations of List
at runtime . This way you don't have to write a separate method remove()
for each List
implementation as long as the object passed to this method implements List
.
Also read:
Upvotes: 5