Avanish Gupta
Milo Chang
A a = new C();
public class A {
public static void callOne() {
System.out.println("1");
}
public void callTwo() {
System.out.println("2");
}
}
public class B extends A {
@Override
public static void callOne() {
System.out.println("3");
}
@Override
public void callTwo() {
System.out.println("4");
}
}
public class Main {
public static void main(String[] args) {
A a = new B();
a.callOne();
a.callTwo();
}
}
callOne()
, which is static, and callTwo()
, which is not static. The methods in B override those of A. We have made an object with static type A and dynamic type B. When calling callOne()
and callTwo()
, what will be printed? callOne()
is static while callTwo()
is not. Because callOne()
is static, when we call it from a
, we use its static type, so callOne()
from class A is called and "1" is printed. Meanwhile, because callTwo()
is not static, when we call it from a
, we use its dynamic type, so callTwo()
from class B is called and "4" is printed. Β© 2024 Fiveable Inc. All rights reserved.