Inheritance in Java – Complete Guide
? What is Inheritance in Java?
Inheritance is one of the most important features of Object-Oriented Programming (OOP) in Java. It allows one class (called the child or subclass) to inherit the properties and behaviors (fields and methods) of another class (called the parent or superclass). This helps in code reusability, method overriding, and makes the program easier to manage and extend.
🏗️ Java Inheritance Types
Interactive Visual Guide to Object-Oriented Programming Concepts
💡 Key Takeaways
Single, Multilevel, Hierarchical
Multiple Inheritance (use Interfaces)
Prefer composition over inheritance
⭐ Why Use Inheritance in Java?
📋 Types of Inheritance in Java
1 Single Inheritance in Java
In this type, one class inherits another class.
class Animal {
void sound() {
System.out.println("Animals make sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // From Animal class
d.bark(); // From Dog class
}
}
Animals make sound Dog barks
- Dog class extends Animal, so it can use the sound() method from the Animal class.
- This is called single inheritance because only one parent is inherited by one child.
2 Multilevel Inheritance in Java
In this type, a class inherits another class, which in turn inherits another class.
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Puppy weeps");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // From Animal
p.bark(); // From Dog
p.weep(); // From Puppy
}
}
This animal eats food Dog barks Puppy weeps
- Puppy inherits from Dog, and Dog inherits from Animal.
- All properties and methods are available to the Puppy class.
3 Hierarchical Inheritance in Java
In this type, multiple classes inherit from one parent class.
class Animal {
void sound() {
System.out.println("Animals have different sounds");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
d.sound();
d.bark();
c.sound();
c.meow();
}
}
Animals have different sounds Dog barks Animals have different sounds Cat meows
- Dog and Cat both extend the Animal class.
- This is known as hierarchical inheritance.
4 Multiple Inheritance Using Interfaces
Java does not support multiple inheritance with classes to prevent ambiguity (like the Diamond Problem), but it supports multiple inheritance using interfaces.
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}
Method A Method B
- Class C implements two interfaces, A and B.
- No ambiguity since both are interfaces and Java handles them well.
🔑 Super Keyword in Inheritance
super
is used to refer to the parent class. It can be used to:
class Animal {
String color = "White";
Animal() {
System.out.println("Animal is created");
}
void displayColor() {
System.out.println("Animal color: " + color);
}
}
class Dog extends Animal {
String color = "Black";
Dog() {
super(); // calls Animal constructor
System.out.println("Dog is created");
}
void printColor() {
System.out.println("Dog color: " + color);
System.out.println("Animal color using super: " + super.color);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.printColor();
}
}
Animal is created Dog is created Dog color: Black Animal color using super: White
🔄 Method Overriding in Inheritance
When a subclass provides its own version of a method from the superclass, it's called method overriding.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Calls Dog's overridden method
}
}
Dog barks
- Though the reference is of type Animal, the object is Dog.
- The Dog class's method is executed due to runtime polymorphism.
⚠️ Why Java Does Not Support Multiple Inheritance with Classes
Java does not support multiple inheritance with classes directly, and there's a solid reason behind it—to avoid ambiguity and complexity in code. This problem is famously known as the Diamond Problem.
What is the Diamond Problem?
Imagine you have three classes:
class A {
void show() {
System.out.println("A's show method");
}
}
class B extends A {
void show() {
System.out.println("B's show method");
}
}
class C extends A {
void show() {
System.out.println("C's show method");
}
}
Now, what if you try to create a class D that extends both B and C?
class D extends B, C { // Not allowed in Java
// Confusion: Which show() should D inherit?
}
Both B and C have their own versions of the show() method. If class D inherits from both, the compiler gets confused—which show() method should be called?
- From B?
- Or from C?
This ambiguity leads to confusion, bugs, and makes the code harder to maintain and understand.
🔧 How Java Solves Multiple Inheritance
Understanding Java's Approach to Avoiding the Diamond Problem
🎯 Java's Solution Strategy
Single Inheritance
with Classes
Multiple Inheritance
through Interfaces
Key Insight: Interfaces in Java only declare methods, they don't implement them. So when a class implements multiple interfaces, it must provide its own implementation, eliminating any ambiguity!
💡 Example Using Interfaces (No Ambiguity)
🤔 Why no confusion?
Because class C provides its own implementation of show()
,
and interfaces do not carry method bodies (until Java 8, which introduced default methods,
but even those can be overridden to resolve conflicts).
🎯 Conclusion
Instead of forcing multiple inheritance, Java gives you interfaces and default methods for flexibility—without compromising clarity and maintainability.
🌟 Final Words on Inheritance in Java
Inheritance helps reduce code duplication, enables polymorphism,
and makes programs modular and maintainable. Java supports different types of inheritance
(except multiple inheritance with classes) and uses powerful features like super
and method overriding to give developers better control over code behavior.
❓ FAQs about Inheritance in Java
1. What is the main purpose of inheritance in Java?
To allow a class to use the properties and methods of another class, reducing redundancy and improving code structure.
2. Can we inherit constructors in Java?
Constructors are not inherited, but you can call the parent constructor using the super()
keyword.
3. What is the difference between "extends" and "implements"?
• extends
is used to inherit from a class.
• implements
is used to implement an interface.
4. Can a class extend more than one class in Java?
No, Java does not support multiple inheritance using classes to avoid conflicts.
5. How do you achieve multiple inheritance in Java?
You can use interfaces to achieve multiple inheritance in Java.
🔗 extends vs implements
Understanding Java's Key Inheritance Keywords
For Class Inheritance
✨ Key Features:
- Inherits all public/protected methods and fields
- Can override parent methods
- Single inheritance only (one parent class)
- Child IS-A relationship with parent
For Interface Implementation
🔧 Key Features:
- Must implement all interface methods
- Can implement multiple interfaces
- Provides contract/blueprint
- Class CAN-DO relationship with interface
0 Comments
If you have any doubts, Please let me know