I was studying polymorphism and had an issue of not knowing when the program is in compile time stage or run time stage.

I know that the compiler looks at the code during compile time it turns it into bytecode to be executed during run time but when initializing an object via super class reference to a subclass object at compile time the compiler only knows that its a reference to the super class for example:

public class SuperClass extends Object {
    public void method1()
        System.out.printlin("executed from the superClass");
}

public class SubClass extends superClass {
    public void method1()
        System.out.printlin("executed from the subClass");
}
...

and in the main class :

SuperClass sup = new subClass();
sup.method1;
...

Now my problem is that if the compiler (at compile time) only knows that sup is a SuperClass reference then when sup.method1; gets called at compile time it looks in the SuperClass and execute the original method1 but at runtime the compiler knows that sup is an object of type SubClass so it looks for the method1 inside the supclass and execute the overridden version of method1 but and my problem is that i fail to understand in which stage is the sup.method1; gets executed, at run time or compile time?

And I know that if you are in compile time you can do casting to make the compiler execute method1 from the supclass but if the sup.method1 execute at run time then whats the point of casting anyway?

Note: excuse my poor terminology I am still new to the whole inheritance / polymorphism concepts.

1 Answers

0
Community On

The compiler does not execute the code during compilation; the method is executed at runtime.
The sup objects actual type will always be SubClass, but it can be referred to as its supertype, as in your example.

It is not possible to cast the sup object to make it call method1 from SuperClass. Casting only changes the type you use to refer to the object, not the actual type of the object itself.
One use for casting could be if SubClass had another method, method2, which was not present in SuperClass. If you then had a reference to a SubClass instance, through a SuperClass reference, you would not be able to call method2 without casting (downcasting) the reference to a SubClass first.