<< Hide Menu
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
Now that we have established a little bit about polymorphism in the last topic, let's talk some more about it. Every object has a static type and a dynamic type. Let's use the hierarchy tree from the last topic:
A a = new C();
As we can see, the object has two types given to it, A, which is the type the variable is declared as, and C, which is the type that the constructor is calling. The type that the variable is declared as is known as the variable's static type, while the type of the constructor call is known as the variable's dynamic type. These will be useful to know when calling methods.
Before we move on, consider the following code:
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();
}
}
Here, we have two classes, A and B, where A is a superclass of B. They each have two methods, 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?
The key lies in mentioning that 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.