+ 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(); } }

31st Jan 2022, 9:30 AM
Davinder Kumar
Davinder Kumar - avatar
4 Respuestas
+ 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();
31st Jan 2022, 10:37 AM
Avinesh
Avinesh - avatar
+ 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.
31st Jan 2022, 10:24 AM
Rishi
Rishi - avatar
+ 1
but when i invoke method1() it doesn't throw any error why is that ????
31st Jan 2022, 9:36 AM
Davinder Kumar
Davinder Kumar - avatar
+ 1
Thank you both of you... finally i got to know about this concept briefly.
31st Jan 2022, 10:45 AM
Davinder Kumar
Davinder Kumar - avatar