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 ! } }
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
+ 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.