Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi EveryOne,

I had following question.

Java
Class A{
public void Test(){
System.out.println("In A Class Test Method");
}
}

Class B extends A{
public void Test(){
System.out.println("In B Class Test Method");
}
}
Class MainMethod{
public static void main(String [] args){
A a = new B();
 a.Test();//This will call the B class Test Method
}
}
}


In the above example which is a dynamic polymorphism case the method to be called is decided by the object created(in above case B Class Test Method will be called since I create B Class Object).Now I want to call the method of A Class without making any changes to the code.Is it possible?If not then how it can be said to be dynamic polymorphism as by seeing the object created we can easily say tha B Class Test Method wil be called

Thanks
Posted

1 solution

first of all you have to understand the meaning of dynamic polymorphism. The behaviour of the Object should be determined at runtime. In your code , by only watching the following line ,
Java
a.test();
, one can't predict which method can be called. However as per your simple example , you can easily say that it might call Class B's test() method , But think it little bit in large scenario. Suppose Class A has lots of sub classes,say Class B, Class C, .. Class N and there is a method something like :

Java
public void getResult(A object){
  //some code
  object.test();//say line no 3
  //some code
}



In this example can you able to say which test() method should be called. So no body can predict.
This can only be determined at runtime.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900