I'm currently learning about Java and I encountered this particular function called method overriding. When do I need to override something from the parent class if I can just create a new function?
class Animal{
boolean alive;
void speak(){
System.out.println("This animal speaks");
}
}
class Dog extends Animal{
@Override
void speak(){
System.out.println("The dog goes *bark*");
}
}
why is there a need to override a method when I can just make a new method in the dog class?
class Dog extends Animal{
void bark(){
System.out.println("The dog goes *bark*");
}
}
You override a method when you have a class hierarchy, as you do, where there is a sensible default behaviour which many of your subclasses will want to use, but some subclasses need different behaviour and you want to call the method using a reference of the base class.
If I had code like:
Dog d = new Dog();
d.speak();
Then just implementing bark()
would be fine, because d
is always a Dog
.
But when I have code like this:
Animal a;
if (...) {
a = new Dog();
} else {
a = new Cat();
}
a.speak();
Then we have to override a method. If the subclasses had a new method (like your bark()
) which wasn't present on Animal
we wouldn't be able to call it, because a
is an Animal
-- the actual object it refers to might be a Dog
or a Cat
.