Java Inheritance
Inheritance lets a class (subclass) acquire fields and methods from another class (superclass), using the `extends` keyword. This promotes code reuse and models 'is-a' relationships.
A subclass can add new fields/methods and override inherited methods to provide specialized behavior, using the `super` keyword to reference the parent class.
class Sub extends Super {
Sub() { super(); }
}extends keyword
Class B extends class A to inherit its non-private members. B is called the subclass (or child), A is the superclass (or parent).
super keyword
super() calls the parent's constructor, and super.method() calls the parent's version of an overridden method.
class Animal {
void eat() { System.out.println("This animal eats food"); }
}
class Dog extends Animal {
void bark() { System.out.println("Woof!"); }
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}This animal eats food
Woof!Dog inherits eat() from Animal and adds its own bark() method.
Key points
- extends creates a subclass that inherits from a superclass.
- Subclasses inherit non-private fields and methods.
- super() calls the parent constructor.
- Inheritance models 'is-a' relationships.
