πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ–²

9.6 Polymorphism

2 min readβ€’january 3, 2023

Milo Chang

Milo Chang

Peter Cao

Peter Cao

Milo Chang

Milo Chang

Peter Cao

Peter Cao


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Static and Dynamic Types

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:
https://firebasestorage.googleapis.com/v0/b/fiveable-92889.appspot.com/o/images%2F-buy28OuxvWUq.png?alt=media&token=fded642b-b752-4ddb-beae-77ff07362fd0

Courtesy of Wikimedia Commons.

Let's make an object a with the following constructor call:
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.

Method Calling and Polymorphism

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.
Browse Study Guides By Unit
βž•Unit 1 – Primitive Types
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–±Unit 10 – Recursion
πŸ™Exam Reviews