Sub topic 12
Override Instance Methods
A child class can provide its own version of a method from a parent class. This is called overriding. It lets related objects respond differently to the same method call.
For example, both a dog and a cat are animals, but they can make different sounds. A program can treat both as animals and still get the right sound from each one.
Parent and child classes
A class is a plan for creating objects. An object is an instance created from a class. An instance method is a method called on an object.
Inheritance is a way to create a new class based on an existing class:
- The parent class is the existing class.
- The child class is the new class. It inherits accessible methods from the parent.
- The child can override an inherited instance method to provide different behavior.
In Java, the word extends creates this parent-child relationship. For example, Dog extends Animal means that Dog is a child of Animal.
A dog is still an animal. So a variable of type Animal can refer to a Dog object. A reference is a value that points to an object.
A working example
This program defines an Animal parent class and two child classes. Each child overrides the speak method.
Save it in a file named OverrideDemo.java.
class Animal {
public String speak() {
return "An animal makes a sound.";
}
}
class Dog extends Animal {
@Override
public String speak() {
return super.speak() + " Woof!";
}
}
class Cat extends Animal {
@Override
public String speak() {
return "Meow!";
}
}
public class OverrideDemo {
public static void main(String[] args) {
Animal[] animals = {
new Animal(),
new Dog(),
new Cat()
};
for (Animal animal : animals) {
System.out.println(animal.speak());
}
}
}Compile and run it from the folder that contains the file:
javac OverrideDemo.java
java OverrideDemoThe output is:
An animal makes a sound.
An animal makes a sound. Woof!
Meow!The array is a group of values. Here, every entry has the declared type Animal, but the entries refer to different kinds of objects. The loop calls speak() on each one.
The first object uses Animal.speak(). The dog uses Dog.speak(), and the cat uses Cat.speak().
The role of `super`
In Dog.speak(), the expression super.speak() calls the parent class’s version of speak on the same dog object. The dog method then adds " Woof!" to the result.
A child method does not have to call the parent method. Cat.speak() replaces the inherited behavior without calling super.speak().
How Java chooses the method
The compiler is the tool that checks Java source code and translates it so the program can run. When it checks animal.speak(), it sees that the variable animal has type Animal. It checks that Animal has an accessible speak method.
At run time, when the program is executing, Java looks at the actual object. If that object is a Dog, Java runs the dog’s override.
This run-time choice is called dynamic dispatch.
For example, consider a variable declared like this:
class ReferenceDemo {
public static void main(String[] args) {
Animal pet = new Dog();
System.out.println(pet.speak());
}
}
class Animal {
public String speak() {
return "An animal makes a sound.";
}
}
class Dog extends Animal {
@Override
public String speak() {
return "Woof!";
}
}Save this example as ReferenceDemo.java. It prints Woof!. The variable’s declared type is Animal, but the object was created as a Dog.
The declared type still matters. Even if Dog had a method named fetch, a call to pet.fetch() would not compile unless Animal also made that method available. The compiler checks what the declared type allows.
If a child class does not override a method, it uses the inherited version. For example, an Animal child with no speak method would use Animal.speak().
Rules for overriding
An override must match the parent method in important ways.
Name, parameters, and return type
The method name must be the same. Its parameter types must also be the same and in the same order. A parameter is a named input in a method declaration. The parameter names may differ.
The return type tells Java what kind of result a method gives back. Usually, an override uses the same return type as the parent method. There is one useful exception: if the parent returns an object type, the child may return a more specific compatible object type. For example, a parent method that returns Animal may be overridden by one that returns Dog.
A method declared with void does not return a value. Its override must also use void. A method that returns a primitive type, such as int, must keep that same return type.
Access
An access modifier controls where a method can be used. For example, public makes a method available from any class that can access its class.
An override cannot make an inherited method less accessible. A public parent method must stay public in the child. A protected parent method can stay protected or become public.
A private method is available only inside its own class. A child does not inherit it and cannot override it. A method with no access modifier is package-private: it is available within its package. A package is a group of related Java classes. Such a method is not inherited by a child in a different package.
Methods that cannot be overridden
A method marked final cannot be overridden. This lets a class keep that method’s behavior fixed in its child classes.
A static method belongs to a class rather than to an individual object. A child can declare a static method with the same name and parameters, but this is called hiding, not overriding. It does not use the object-based choice shown in the animal example.
Use `@Override` to catch mistakes
@Override is an annotation: a note in Java code that gives the compiler information. It tells the compiler that the method is intended to override an inherited method.
The annotation is optional, but it is a good habit. If the method does not actually override one from the parent, the compiler reports an error. That can catch a spelling mistake or a wrong parameter type.
For example, if the parent method is named speak but the child method is accidentally named speek, the two names do not match. With @Override, the compiler catches the mistake.
Overriding is not overloading
Overriding changes an inherited instance method in a child class. The method name and parameter types match the parent method.
Overloading means having methods with the same name but different parameter lists. For example, speak() and speak(String word) are different overloads. Adding speak(String word) to Dog does not override Animal.speak(), because their parameters differ.
Java chooses an overload using the types known to the compiler. After that, an overridden instance method is chosen using the actual object at run time. Keeping these two choices separate helps explain which method will run.
Keep the method’s promise
A method’s contract is the behavior that callers can expect from it. An override should respect the parent method’s contract.
For example, suppose an Animal.speak() method promises to return a description of a sound. A child override should also return a sound description. Code that works with an Animal should not have to know every child class in order to use speak() safely.
Overrides also have a rule about checked exceptions. An exception is a problem a method can report. A checked exception is one that Java requires code to handle or declare. An override cannot declare a broader checked exception than the parent method allows. It may declare a narrower one, or none.
Common mistakes
| Mistake | What to check |
|---|---|
| A parent method runs instead of the child version | Check the child method’s name and parameter types. Add `@Override` to catch a mismatch. |
| A child method will not compile | Check that its return type and access are allowed by the parent method. |
| A method works on a `Dog` variable but not an `Animal` variable | The compiler checks methods available through the variable’s declared type. |
| A static method seems to ignore the object’s class | Static methods are hidden, not overridden. |
| A child cannot override a method | Check whether the parent method is `private` or `final`. |
Practice
Exercise
In the first example, what does animal.speak() return when animal refers to a Cat object? Why?
Show answer
It returns "Meow!". The actual object is a Cat, so dynamic dispatch selects Cat.speak().
Exercise
Animal has a public speak() method. Can Dog override it with a private speak() method?
Show answer
No. An override cannot make the method less accessible. The Dog method must also be public.
Exercise
Animal has speak() with no parameters. Does a Dog method named speak(String word) override it?
Show answer
No. The parameter lists differ, so speak(String word) is an overload, not an override.