+ 3

Why override in Java?

In Java, you can have a class that extends another. The superclass has a method, example "eat". The subclass can also override the eat method. Why override when it works just as fine to not have the function in the superclass? why have the eat function in the superclass if it's just going to be overriden?

18th Jun 2018, 4:07 PM
kms
kms - avatar
8 Réponses
+ 3
To simplify, think about that: You create 3 subclass of animal: human, dog, cat, with an 'eat' method in their superclass: void eat() { chew(int teeth); } You are inheriting 'eat' for all the subclass, and for example depending on how many teeths have the subclass, it will eat faster. Then you want to create another subclass: snake, but it swallows, so you override ONLY this subclass: eat{ swallow(double measure_of_body); } You can add other animals and decide their eat method, the "default" given by the superclass or a new one. Of course, you can write the same method in each subclass, but is more work, more code, not encapsulated and worse readable (and may not work properly in other examples). Don't do this. Hope this helps you! P.D.: There are many more important reasons as John Wells told you, but i tried to make it easy to understand.
19th Jun 2018, 12:26 AM
ZxZ
ZxZ - avatar
+ 12
It's not mandatory to override methods in subclass. If you want eat() function in subclass to behave exactly as the eat function in superclass, don't override it. It'll inherit the base method automatically. If you want it to behave in different way, only then you need to override.
18th Jun 2018, 4:16 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
To continue with eat, the super class may have a loop with a sleep, hunt, eat cycle that doesn't get overridden. Without an eat method, you couldn't code that cycle so you'd have no choice.
18th Jun 2018, 4:21 PM
John Wells
John Wells - avatar
+ 2
Thanks!
19th Jun 2018, 4:03 AM
kms
kms - avatar
+ 1
The main reason to override is because you can have multiple subclass(e.g.:snake, dog, fish...) of the same superclass(animal), with different ways to deal with 'eat' method (a snake don't 'eat' like a dog, or a fish...), assuming they all are animals and all the animals 'eat' in their own way.
18th Jun 2018, 4:47 PM
ZxZ
ZxZ - avatar
+ 1
look up runtime polymorphism and upcasting
18th Jun 2018, 4:55 PM
Max
Max - avatar
0
But Why have an eat method in the superclass?
18th Jun 2018, 10:31 PM
kms
kms - avatar
0
Check out this simple code: https://code.sololearn.com/c2JXKUvGGDhR/?ref=app and think that programs will become more and more complex -not difficult, but very complex-, and you have to deal with a big amount of data. Encapsule all that you can!!
19th Jun 2018, 2:11 AM
ZxZ
ZxZ - avatar