Lesson 19 of 36Article17 min
Inheritance & super
Child class extends parent: class Dog extends Animal. Child inherits fields and methods (except private).
Inheritance — extends parent class
Child class extends parent: class Dog extends Animal. Child inherits fields and methods (except private).
Use extends once per class in Java — single inheritance.
Real-life example: Dog inherits from Animal — all dogs eat and sleep (parent), but also bark (child extra).
Basic inheritance
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
Dog d = new Dog();
d.eat();
d.bark();super — call parent constructor or method
super() calls parent constructor — must be first line in child constructor if used.
super.methodName() calls parent version of an overridden method.
Real-life example: super is asking your parent for help — "use Dad's recipe step first, then add my spice."
super keyword
class Person {
String name;
Person(String name) { this.name = name; }
}
class Employee extends Person {
int id;
Employee(String name, int id) {
super(name);
this.id = id;
}
}