Cat adds a field, lives. Its constructor first calls super, with the name, so Animal can set it up. That must be the first line. Then it sets its own field. In describe, super dot eat calls the parent's eat method.
Main.javajava
public class Cat extends Animal { private int lives; public Cat(String name, int lives) { super(name); this.lives = lives; } public void describe() { super.eat(); System.out.println(name + " has " + lives + " lives."); }}
We create a cat, with nine lives. Run it. Tom eats, using Animal's method, and then reports his lives.
Main.javajava
public class Main { public static void main(String[] args) { Cat tom = new Cat("Tom", 9); tom.describe(); }}
Output
Tom is eating.
Tom has 9 lives.
Also uses Animal.java
public class Animal { protected String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println(name + " is eating."); }}
Also uses Cat.java
public class Cat extends Animal { private int lives; public Cat(String name, int lives) { super(name); this.lives = lives; } public void describe() { super.eat(); System.out.println(name + " has " + lives + " lives."); }}
Super with brackets calls the parent's constructor. It must be the very first line of the child's constructor. If you don't write it, Java calls the empty parent constructor for you. And super dot method calls the parent's version of a method.
Super calls the parent's constructor, on the first line, and super dot method calls the parent's methods. Next, replacing a parent's method, with overriding.