Overriding and Hiding Methods
Method overriding
is when the subclass redefines a method that is already defined in the superclass. Now this raises the question of which method will be called?
Let's look at an example on method overriding. We will use the Animal and Cat class for this example.
Animal.java
public class Animal {
void makeSound(){
System.out.println("Animal making a sound");
}
}
Cat.java
public class Cat extends Animal {
}
The Cat extends(inherits) the Animal class. Let's instantiate the Cat class and call the makeSound method.
Cat cat = new Cat();
cat.makeSound();
Output : Animal making a sound
Now lets extends the makeSound method and make it more specific to the Cat. Here is the new Cat class definition :
Cat.java
public class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
Let's call makeSound again :
Cat cat = new Cat();
cat.makeSound(); // Outputs Meow
Output: Meow
So from the above, you can notice that the compiler calls the Cat's makeSound not its supercalss makeSound defined in the Animal class.
Calling Superclass methods from subclass
What if in the above we still wanted to call the makeSound method from the Animal class in the Cat class. the super keyword is used to refer to the instance of the superclass.
Cat.java
public class Cat extends Animal {
@Override
void makeSound() {
super.makeSound();
System.out.println("Calling from Cat");
}
}
Output :
Animal making a sound
Calling from Cat
We called the makeSound from the Animal class with super.makeSound();
@Override
Annotation
@Override
is used to hint the compiler that the override was not accidental. We know we are redefing the method in the subclass.
Hiding Fields
When the subclass redefines the same field as defined in the superclass, the superclass field will be hidden when accessed with the subclass object. This is not a recommend practise
To reference the superclass field, the super keyword should be used as follows :
super.fieldname
Hiding Static Methods
If the subclass redefines the same static method as defined in the superclass, then the static method from the superclass will be hidden.
Animal.java
public class Animal {
static void doAnimalthings(){
System.out.println("Doing animal things");
}
}
Cat.java
public class Cat extends Animal {
static void doAnimalthings(){
System.out.println("Doing cat things");
}
}
If we call the static method doAnimalthings on Cat as follows :
Cat.doAnimalthings(); //outputs Doing cat things
Output : Doing cat things
To call the doAnimalthings static method in the Animal class, we will have to use the Animal class as follows :
Animal.doAnimalthings(); //outputs Doing animal things
Output : Doing animal things