Search code examples
javapolymorphismrun-time-polymorphism

why cant we use a reference variable of super class to access methods of its subclass(methods not available in super class)?


I know that,No matter what the actual object is,that the reference variable refers to,The methods i can call on a reference is dependent on the declared type of the variable (in line 15 of code).I want to know why so.Why can't the class user use the reference variable s of type Shape to call its subclass method drawCircle()?

    public class Shape{
            public void displayShape(){
               System.out.println("shape displayed");
                      }
    public class Circle extends Shape{
            public void drawCircle(){
                System.out.println("circle drawn");
                      }
    public class Test{
            p.s.v.main(String[] a){
            Circle c=new Circle();
            Shape s=new Shape();
            display(c);
            display(s);
            public void display(Shape myShape){
               myShape.displayShape();//possible for ref variable c and s
               myShape.drawCircle();//not possible for reference var s
               }
             }
         }

Can u provide me an explanation of what happens at the object level?I am new to java.


Solution

  • The compiler just knows that myShape is a reference variable of type Shape, which contains only one method displayShape() , so according to the compiler, it is not possible to call a method drawCircle() which the Shape class does not contain.

    The compiler is not concerned with what object this variable will hold at runtime. You may extend another class from the Shape class at some later point of time, and use the myShape reference to hold that subclass object. The compiler is just concerned with what type myShape is at compile-time.

    If your Circle class happened to override the displayShape() method, like below :

    public class Circle extends Shape {
        public void displayShape() {
            System.out.println("I am a Circle!");
        }
    
        public void drawCircle() {
        // Implementation here
        }
    }
    

    the only decision happening at runtime would be which displayShape() method to call.