Java Inheritance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java Inheritance

Can we call methods of sub-class by creating an object of child-class with parent-class as it's reference ? i.e class Parent { void m1() { System.out.println("Parent"); } } class Child extends Parent { void m2() { System.out.println("Child"); } } public class Test { public static void main(String[] args) { Parent p= new Child (); p.m1(); p.m2(); // I DOUBT IF WE CAN DO THIS ! } }

21st Apr 2017, 7:45 AM
Preet Patel
Preet Patel - avatar
2 Answers
+ 2
You would need to cast the reference to subclass for you to be able to access the sub class specific method. The compiler only checks for syntactical logic. It doesn't know the superclass reference is an actual subclass
21st Apr 2017, 11:02 AM
Rahul S
Rahul S - avatar
+ 2
The sub class method would only get invoked DYNAMICALLY if the sub class had a similar implementation as that of the super class //m1() in this case The super class has no clue( obviously )about sub class specific methods. Compiler only checks for syntax.
21st Apr 2017, 11:21 AM
Rahul S
Rahul S - avatar