Inheritance
Inheritance types, the super keyword, method overriding, and access modifiers in inheritance.
Definition
Inheritance allows a class (subclass) to acquire the properties and methods of another class (superclass). It promotes code reuse and establishes an “is-a” relationship.
class Subclass extends Superclass {
// additional fields and methods
}
Types of Inheritance
- Single — One subclass extends one superclass.
- Multilevel — A subclass extends another subclass (chain).
- Hierarchical — Multiple subclasses extend the same superclass.
Java does not support multiple inheritance of classes. Use interfaces instead.
The super Keyword
super.method()— Calls the superclass version of an overridden method.super(args)— Calls the superclass constructor from a subclass constructor.
Method Overriding
A subclass provides its own implementation of a method already defined in the superclass. The method signature must match exactly.
Access Modifiers in Inheritance
publicandprotectedmembers are inherited.privatemembers are not directly accessible in subclasses.- Default (package-private) members are inherited only within the same package.
Example
// InheritanceDemo.java
// Demonstrates inheritance and method overriding in Java.
// Superclass
class Animal {
// Method in superclass
void eat() {
System.out.println("Animal eats");
}
}
// Subclass extends superclass
class Dog extends Animal {
// Overriding method
void eat() {
System.out.println("Dog eats bones");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Create Dog object and call eat()
Dog d = new Dog();
d.eat();
}
}
Full source:
examples/09-inheritance/InheritanceDemo.java