The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › Classes and objects
Polymorphism and method selection
Who decides which method runs, and when?
Why it exists — When different kinds of objects must behave differently, without polymorphism you must check the kind of each object one by one with if or switch and branch, and every time a kind is added you must find and change all of those branches. Polymorphism lets you call the same method through a supertype and have the actual object run it in its own way, so that the differences are expressed by overriding the method in each subclass instead of by branches.
Where it's used today — It is used when you split code that does the same job in several ways, such as payment methods or notification methods, into one interface and several implementation classes. Spring injecting a bean by an interface type or passing all the implementations of the same interface together as a List, and handling a collection through a variable of type List, also rely on this property.
The declared type of a variable and the type of the object that it actually refers to can be different. An overridden method is chosen at run time by looking at the actual object, but overloading, static methods, and fields are decided at compile time from the declared type alone.
Checked against real execution · Every combination was compiled and run on JDK 21 and checked against the result
Concepts in this lab
- Polymorphism
- This is the property that calling the same method through a reference of the same type runs different behavior depending on the kind of the actual object. A variable of a supertype (an interface or a superclass) can refer to objects of several subtypes, and which implementation runs is decided at run time (dynamic method lookup). It lets you add a new implementation without changing the calling code.
- Overriding
- Why it exists — When an inherited method does not fit a subclass, creating a new method with a different name means that code calling through the supertype still runs the old inherited behavior. Overriding redefines the method with the same signature so that the new behavior runs even when it is called through the supertype.
- Where it's used today — It is used when you rewrite toString, equals, and hashCode to suit a class, and when you implement the methods of an interface. If you add @Override, the compiler catches the mistake of writing the name or parameters wrongly and ending up with a new method.
- This means that a subclass redefines a method of its superclass (or of an interface) with the same signature. At run time, the method that matches the type of the actual object is called, and this is how polymorphism is implemented. The access level cannot be made narrower, and static, private, and final methods cannot be overridden.
- Overloading
- Why it exists — Without overloading, methods that do the same job would need a different name for each type or number of values they accept, and the calling side would have to know all those names. Overloading groups them under one name and leaves the choice to the compiler.
- Where it's used today — System.out.println, which accepts int, String, and Object, and String.valueOf are common examples. It is also used when you provide several constructors so that an object can be created with some values left out.
- This means defining several methods with the same name but with a different number or different types of parameters. Which method is called is decided at compile time from the types of the arguments. Methods that differ only in return type are not overloaded; that is a compile-time error.
- static
- This keyword marks a member as belonging to the class, not to an instance. A static field exists only once per class and is shared by all instances, and a static method is called without creating an object. A static field whose value changes is effectively a global variable, so it easily causes problems when several threads access it at the same time.
- Inheritance
- This means defining a new class (the subclass) that receives the fields and methods of an existing class (the superclass). It reuses common code, and the subclass adds or overrides only the parts it needs. A Java class supports single inheritance only, and a change to the superclass affects every subclass, so it is best used only when there is a clear "is-a" relationship.
Try these
- Default settings — A Dog object in an Animal variable. For the overridden method, the one in Dog runs.
- Passing the same variable to an overloaded method — print(Animal) is selected even though the actual object is a Dog.
- A static method — It is not overridden. The one in the declared type is called.
- A field — Polymorphism does not apply to fields either.
- Changing the declared type to Dog — With overloading, print(Dog) is selected.
- An Animal object in a Dog variable — This does not compile.
Running with the default settings
- Compile time: Animal a = new Dog(). The declared type of the variable a is Animal, and when the code runs, an object of class Dog is created on the heap. The two are different.
- Compile time: The compiler checks only whether the declared type Animal has sound(). It does not decide which class's sound() will run, and it leaves only the instruction "call sound()".
- Run time: The JVM checks the class of the actual object that a refers to (Dog), and it finds and runs the sound() of that class (dynamic method lookup).
Result of this run
- An overridden instance method is selected by the type of the actual object, not by the declared type of the variable. This is polymorphism, and it is the principle that lets Spring run an implementation that was injected as an interface type.
Code
class Animal {
String name = "animal";
void sound() { System.out.println("Animal.sound"); }
static void info() { System.out.println("Animal.info"); }
}
class Dog extends Animal {
String name = "dog"; // a field with the same name
@Override
void sound() { System.out.println("Dog.sound"); }
static void info() { System.out.println("Dog.info"); }
}
class Printer {
void print(Animal x) { System.out.println("print(Animal)"); }
void print(Dog x) { System.out.println("print(Dog)"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
Assumptions of this model
The output of every combination was checked against the result of actually compiling and running the same code on JDK 21. Calling a static method through a variable, as in a.info(), is allowed by the syntax but is not a recommended practice, and it is included here to show that the call is decided by the declared type.
Previous lab: Inheritance and overriding · Next lab: Interfaces and abstract classes