Sub topic 11
Distinguish Overloading and Hiding from Overriding
This chapter assumes you know how to write a subclass with extends, how to override a method, and how @Override works. You will learn to tell three look-alike features apart: overriding, overloading, and hiding. Beginners often mix them up. The mix-up causes bugs that compile cleanly and then print the wrong thing.
Three Features That Look Alike
Each feature involves two members in a class family that share a name.
- Overriding means a subclass replaces an inherited instance method with the same name and the same parameter types.
- Overloading means one class has several methods with the same name but different parameter lists.
- Hiding means a subclass declares a static method or a field with the same name as one in its superclass. The new member does not replace the old one. It sits next to it.
The key question is how Java chooses which member to use. Java picks an overridden method at run time, using the real type of the object. It picks overloaded methods, hidden static methods, and hidden fields at compile time, using the declared type of the variable.
Overloading: Same Name, Different Parameters
A method's signature is its name plus its parameter types. The return type is not part of it. Two methods in the same class family can share a name if their parameter lists differ. That is overloading.
class Printer {
String show(int value) {
return "int: " + value;
}
String show(String value) {
return "String: " + value;
}
String show(int a, int b) {
return "two ints: " + a + ", " + b;
}
}
public class OverloadBasics {
public static void main(String[] args) {
Printer p = new Printer();
System.out.println(p.show(7));
System.out.println(p.show("seven"));
System.out.println(p.show(3, 4));
}
}The compiler looks at the arguments you pass and chooses the matching method. Nothing about this depends on inheritance. A subclass can also add an overload of an inherited method, and that is where beginners get caught.
The Accidental Overload
Suppose Animal has eat(Object food). A programmer writes eat(String food) in Dog, planning to override it. The parameter type is different, so this is a new method. It does not replace the old one.
class Animal {
String eat(Object food) {
return "Animal eats " + food;
}
}
class Dog extends Animal {
// Different parameter type: this is an overload, not an override.
String eat(String food) {
return "Dog eats " + food;
}
}
public class AccidentalOverload {
public static void main(String[] args) {
Animal a = new Dog();
Dog d = new Dog();
Object food = "bone";
System.out.println(a.eat("bone"));
System.out.println(d.eat("bone"));
System.out.println(d.eat(food));
}
}The output is:
Animal eats bone
Dog eats bone
Animal eats boneHere is why.
ahas the declared typeAnimal. The compiler only seeseat(Object)there, so it picks that method. The object is aDog, butDogdoes not overrideeat(Object), so theAnimalversion runs.dhas the declared typeDog. It sees both methods. The argument"bone"is aString, soeat(String)is the best match.- The variable
foodhas the declared typeObject, even though it holds a string. The compiler chooses by declared type, soeat(Object)is picked.
Overload choice looks at the declared types of the arguments, not the objects they refer to. Overriding is different. It looks at the real type of the receiver object.
Hiding Static Methods
A static method belongs to the class, not to an object. It cannot be overridden. If a subclass declares a static method with the same signature as one in its superclass, the subclass method hides the superclass method.
Hiding Fields
Fields are never overridden either. If a subclass declares a field with the same name as an inherited field, the object holds both fields. The subclass's field hides the superclass's field. Inside the subclass, the plain name refers to the new field, and super.name reaches the old one.
The next program shows both kinds of hiding next to a real override.
class Parent {
String name = "Parent field";
static String who() {
return "Parent static";
}
String me() {
return "Parent instance";
}
}
class Child extends Parent {
String name = "Child field";
static String who() {
return "Child static";
}
@Override
String me() {
return "Child instance";
}
String bothNames() {
return name + " / " + super.name;
}
}
public class HidingDemo {
public static void main(String[] args) {
Parent p = new Child();
Child c = new Child();
System.out.println(p.name);
System.out.println(c.name);
System.out.println(p.me());
System.out.println(Parent.who());
System.out.println(Child.who());
System.out.println(c.bothNames());
}
}The output is:
Parent field
Child field
Child instance
Parent static
Child static
Child field / Parent fieldLook at the first three lines. Both p and c refer to a Child object, yet p.name gives the Parent field. The compiler chooses the field from the declared type Parent. The method call p.me() gives the Child result, because the object's real type decides which overridden method runs.
Call static methods through the class name, as in Parent.who(). If you call p.who() on a variable, Java still uses the declared type of p, not the object. That makes the code look like it behaves polymorphically when it does not.
How Java Decides
The diagram shows the order of decisions for a call like x.go(arg).
Overloading is settled in step C, before the program runs. Overriding is settled in step G, while it runs.
Side-by-Side Comparison
| Feature | Applies to | Same signature? | Chosen when? | Chosen by |
|---|---|---|---|---|
| Overriding | Instance methods | Yes | Run time | Real class of the object |
| Overloading | Methods | No, same name only | Compile time | Declared types of the arguments |
| Static method hiding | Static methods | Yes | Compile time | Declared type of the variable or class name |
| Field hiding | Fields | Not applicable | Compile time | Declared type of the variable |
Rules for Overriding That Rule Out Other Cases
Some details decide which feature you are actually using.
- Changing only the return type is not overloading. Two methods in one class with the same name and parameters but different return types are a compile error.
- When you override, the return type must be the same, or a subtype of the original (a covariant return type). Without that, the code does not compile.
- A
privatemethod is not inherited. A subclass method with the same name is a new, unrelated method, not an override. - A
finalmethod cannot be overridden. A subclass that declares the same signature gets a compile error. Hiding afinalstatic method is also an error. - Hiding a field can use a different type from the original. The two fields are unrelated apart from the name.
Use @Override to Catch Mistakes
Put @Override on every method you mean to override. If the method does not really override something, the compiler stops you. Try it on the accidental overload from earlier.
class Dog extends Animal {
@Override
String eat(String food) { // compile error: method does not override
return "Dog eats " + food;
}
}The error appears immediately, instead of showing up later as the wrong output. @Override on a static method is also an error. That tells you the method hides rather than overrides.
Practical Advice
- Put
@Overrideon every override. - Avoid overloads that differ only by related types, such as
ObjectandString. They are hard to predict. - Do not reuse a field name from a superclass. Pick a new name, or reuse the inherited field.
- Call static methods through the class name.
- When a result surprises you, ask whether the choice was made at compile time or at run time.
Exercise
Given class A with the method void run(Object o) and class B extends A with the method void run(String s), what does this code print, and why? A x = new B(); x.run("hi"); Assume A.run prints "A" and B.run prints "B".
Show answer
It prints "A". The variable x has the declared type A, so the compiler sees only run(Object) and picks it. B.run(String) is an overload, not an override, because the parameter types differ. Dynamic dispatch only chooses among overrides of run(Object), and B has none, so A's version runs.
Exercise
Class P has a field int n = 1; class C extends P has a field int n = 2. After P p = new C(); what does p.n evaluate to, and what does ((C) p).n evaluate to?
Show answer
p.n is 1 and ((C) p).n is 2. Fields are hidden, not overridden, so the field is chosen from the declared type. The variable p has type P, so it reads P's n. The cast to C changes the declared type to C, so it reads C's n. Both fields exist inside the one object.
Exercise
A subclass declares a static method with the same signature as a static method in its superclass. Is this overriding, overloading, or hiding? Which tool can warn you if you mistakenly believe it is overriding?
Show answer
It is hiding. Adding @Override to the subclass method makes the compiler report an error, because static methods cannot be overridden.