package test;
public class Test {
public static void main(String[] args) {
A a2 = new B(); // 1
a2.display1();
a2.display();
((B) a2).display2(); // 2
((A) a2).display(); // 3
B b1 = new B();
b1.display1(); // 4
}
}
class A {
int a = 10;
void display() {
System.out.println("parent class " + a);
}
void display1() {
System.out.println("parent class " + (a + 10));
}
}
class B extends A {
int a = 30;
@Override
void display() {
System.out.println("child class " + a);
}
void display2() {
System.out.println("child class " + (a + 10));
}
}
You do new B()
, so obviously a B
object is created.
Yes, from the type A
to the subtype B
which is down the class hierarchy.
Because a2
refers to a B
object and which method is called is determined dynamically (at runtime, instead of at compile time) by looking at what the type of the actual object is.
No, there's no casting going on here at all.
I don't understand exactly what you mean here. The type of the variable determines which methods you can call, but which method is actually called depends on the actual type of the object that the variable refers to.