Single Inheritance in Java
Single inheritance is the simplest form of inheritance in Java, where one class (the subclass) inherits the fields and methods of exactly one other class (the superclass). It's the foundation that all other inheritance types in Java build on.
Syntax
class Superclass {
// fields and methods
}
class Subclass extends Superclass {
// additional fields and methods
}
Basic Example
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
Dog myDog = new Dog();
myDog.eat(); // inherited from Animal
myDog.bark(); // defined in Dog
Why Use Single Inheritance?
- Avoids code duplication by letting a subclass reuse fields and methods from its parent
- Keeps the class hierarchy simple, predictable, and easy to follow
- Forms the basis for method overriding, where a subclass can customize inherited behavior
Method Overriding in Single Inheritance
A subclass can override a method from its superclass to provide its own specific implementation.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
Using super in Single Inheritance
The super keyword allows a subclass to access the parent class's constructor, methods, or fields directly, even after overriding them.
Single Inheritance vs Other Types
- Single inheritance — one subclass, one superclass
- Multilevel inheritance — a chain of classes, each extending the one before it
- Hierarchical inheritance — multiple subclasses extending the same single superclass
Java only allows a class to extend one other class directly — this restriction to single inheritance at each level is exactly what keeps Java's class hierarchy free of the diamond problem.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.