I know polymorphism happens in the case of method overriding. But I am a little confused about the below.
class A {
public void hi() {
System.out.println("A "+this.getClass().getName());
}
}
class B extends A {
public void bye() {
System.out.println("B "+this.getClass().getName());
}
}
class Ideone {
public static void main (String[] args) throws java.lang.Exception {
A a = new B();
a.hi();
a.bye();
}
}
Output:
Main.java:35: error: cannot find symbol
a.bye();
^
symbol: method bye()
location: variable a of type A
1 error
Why does this give a compile time error?
In a = new B()
, the B
class object is created at runtime, so a
's a reference variable pointing to an object of type B
.
Now if we call B
's class method bye()
, why it is a compiler time error?