Search code examples
javaobjectinheritancepolymorphismabstraction

What is the meaning of SuperClass s=new SubClass();?


Test.java

public class Test {

    public void go(){       
        System.out.println("Test go");
    }
}

Test2.java

public class Test2 extends Test {
public void go(){       
    System.out.println("Test 2 go");
}

public void back(){
    System.out.println("Test 2 back");
    }   
}

class Demo{

    public static void main(String[] args) {

    Test t=new Test2();
    t.go(); // Output : "Test 2 go"
    t.back(); //Compile time error. 
 }

 }

I read some issues on stackoverflow regarding this but I did not understood the meaning of SuperClass s=new SubClass();. Also in output if Object of Test can access the go() method of Test2 then why it cannot access back() method.


Solution

  • This is an example of Polymorphism, which means we can refer to subtype object using reference of super type.

    back() method is not defined for Test type . You are calling back() method on Test type variable which is not valid. When you declare

    Test t = new Test2();
    
    • You are creating a reference variable t of type Test
    • You are referring to an object which is of type Test2 using polymorphic reference.

    Also in output if Object of Test can access the go() method of Test2 then why it cannot access back() method.

    As t is of type Test, it can only know about methods defined in Test class. It cannot know about methods which are defined in subclass Test2

    Regarding your question in comment,

    • When you say t.go(), at compiler is thinking go() method from Test class is being called. At compile time it is not known which object is going to be created.
    • Your declaration Test t = new Test2(); creates Test2 object at runtime, which in turn calls go() method from Test2 because it is overriding go() from Test

    You should really read about compile time polymorphism and runtime polymorphism