zuai-logo

Polymorphism

Emily Wilson

Emily Wilson

4 min read

Listen to this study note

Study Guide Overview

This guide covers static and dynamic types of objects, focusing on how they are determined during object creation. It then explains method calling and polymorphism, illustrating how static and dynamic types influence which method is executed. The guide uses code examples to demonstrate the interaction between static/dynamic types and static/non-static methods.

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:

markdown-image

Courtesy of Wikimedia Commons.png&psig=AOvVaw2elTUnxk5JGLw1X7_9WGgv&ust=1598242386382000&source=images&cd=vfe&ved=0CAMQjB1qFwoTCMDX8fG9sOsCFQAAAAAdAAAAABAD).

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.

Question 1 of 5

Given the declaration Animal cat = new Cat();, which type is the static type of the cat object? 🤔

Cat

Object

Animal

None of the above