Java inheritance with extends, super and @Override, using dogs and cats.
In one line
With extends, a class takes over its parent’s fields and methods as they are and overrides only the parts that differ.
Why you need it
Separate Dog and Cat classes would each carry a name, a meal count and an eat method. Change the eating rule and you must edit both; miss one and the animals start behaving differently.
Keep the shared part once in Animal and write only the real differences, such as the sound, in Dog and Cat. A Rabbit later needs only its own differences.
Everyday picture
Picture a shop chain’s operating manual. Each branch uses the head office manual as it is and swaps only local pages, such as the menu. When a shared rule like opening hours changes, only the head office manual is edited.
Java code does not run on this page. Compile your changed code with javac on your own computer.
When to use it
The sentence "a dog is an animal" sounds right
Several classes share fields and behavior and differ in only a few spots
You want to handle many children through one parent type (next topic: polymorphism)
A Java class has exactly one parent. If "has a" fits better than "is a", put the other object in a field instead (composition).
Common mistakes
Forgetting super(...) in the child constructor
If the parent has no constructor without parameters, the child constructor must start with super(...). Otherwise Java inserts super() for you and fails.
Writing Sound instead of sound just adds another method, so there is no error and the parent’s "..." comes out. Mark it with @Override and javac catches the typo ("method does not override").
Private fields stay visible only inside the parent, even after inheritance. Change them through a parent method, or make them protected if children really need them.
A Cat is stored in an Animal variable. What does introduce() print?
publicclassMain {publicstaticvoidmain(String[] args) {Animal pet = newCat("Coco", false);System.out.println(pet.introduce()); }}
Show the answer
Answer: 3. Coco says Hiss The variable type is Animal, but the object is a Cat, so Cat.sound() runs. indoor is false, so it is "Hiss".
Question 2
What happens with class Puppy extends Dog, Animal { }?
Show the answer
Answer: 2. It does not compile A Java class names exactly one parent after extends. To take on several contracts, implements several interfaces instead.
Questions people ask
How is inheritance different from implementing an interface?
extends takes over fields and method bodies, and there is only one parent. implements takes on a set of method promises, and a class can take many.
Do I have to write @Override?
Code runs without it, but write it anyway. If the name or parameters are wrong, javac reports an error.
When do I use super?
On the first line of a child constructor to call the parent constructor (super(name)), and inside an overriding method to call the parent version (super.sound()).