+ 1
Related to dynamic method dispatch in java ....... when I invoke method2() using Smartphone object in main it throws error
class Phone{ public void method1(){ System.out.println("phone is ringing....."); } } class Smartphone extends Phone{ public void method1(){ System.out.println("smartphone is ringing...."); } public void method2(){ System.out.println("Smartphone is ringing....."); } } public class dispatchoverride { public static void main(String args[]){ Phone obj1=new Smartphone(); obj1.method2(); } }
4 Answers
+ 3
The parent class should have the relevant method which could be executed from a child class object for a runtime polymorphism to happen.
For your code to work, you can downcast it.
((Smartphone)obj1).method2();
+ 2
You are using a reference of type Phone to refer to the Smartphone object. The override feature only allows you to find the most inherited method of the base class, you can't access some method that you've defined newly in some derived class.
Simply put, the reference type Phone can only see the"Phone" part of the "Smartphone" object.
+ 1
but when i invoke method1() it doesn't throw any error why is that ????
+ 1
Thank you both of you... finally i got to know about this concept briefly.