Calling the parent's constructor: super
When the parent has a constructor, the child calls it with super(...) as its very first line:
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
class Manager extends Employee {
int teamSize;
Manager(String name, int salary, int teamSize) {
super(name, salary);
this.teamSize = teamSize;
}
}
public class Main {
public static void main(String[] args) {
Manager m = new Manager("Asha", 90000, 6);
System.out.println(m.name + " manages " + m.teamSize + " people");
}
}Output
Asha manages 6 people
Overriding: doing it differently
A child can override a parent's method – write its own version with the same name and parameters:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
class Cow extends Animal {
@Override
void sound() {
super.sound();
System.out.println("Moo");
}
}
public class Main {
public static void main(String[] args) {
new Animal().sound();
new Cat().sound();
new Cow().sound();
}
}Output
Some sound Meow Some sound Moo
@Overrideis optional but very useful: if you misspell the method name, the compiler warns you.super.sound()runs the parent's version, so the child can add to it instead of replacing it.
Stopping inheritance: final
A final method can't be overridden, and a final class can't be extended. String is a final class.
final class Secret {
}
class Spy extends Secret {
}
public class Main {
public static void main(String[] args) {
}
}Output (the program does not compile)
Main.java:4: error: cannot inherit from final Secret
class Spy extends Secret {
^