Inheritance is one of the core
mechanisms of object-oriented programming in Java. It allows one class to derive from
another class and reuse accessible behavior while adding or specializing its own behavior.
Java uses the extends keyword to establish inheritance
between classes.
Inheritance becomes especially useful when several related classes share common state or behavior. Instead of duplicating that common implementation in every class, you can place shared functionality in a parent class and allow more specific child classes to extend it.
Inheritance also provides the foundation for runtime polymorphism. A parent-type reference can refer to a child object, and an overridden instance method can execute according to the actual object at runtime.
What Is Inheritance in Java?
Inheritance creates a relationship between a parent class and a child class. The child class can use inherited accessible members and can define additional fields and methods of its own.
class Animal {
public void eat() {
System.out.println("Animal eats food");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog barks");
}
}
Because Dog extends Animal, a Dog object can use
the inherited eat() method as well as its own
bark() method.
Dog dog = new Dog();
dog.eat();
dog.bark();
Parent Class and Child Class
The class being extended is commonly called the parent class, superclass, or base class. The class doing the extending is called the child class, subclass, or derived class.
Parent Class
Defines common state and behavior that related child classes can use.
Child Class
Extends the parent class and can add or specialize behavior.
The extends Keyword
Java uses the extends keyword to create
class inheritance.
class Animal {
}
class Dog extends Animal {
}
This means Dog is a subtype of Animal. A Dog object can therefore be treated as an Animal where the parent type is expected.
Animal animal = new Dog();
This relationship is the basis for many Java designs involving polymorphism and abstractions.
What Does a Child Class Inherit?
A subclass can use accessible inherited members from its superclass. However, inheritance does not mean that every member becomes directly accessible everywhere. Java's access rules still apply.
class Animal {
protected String name;
public void eat() {
System.out.println("Eating");
}
private void internalTask() {
System.out.println("Internal task");
}
}
class Dog extends Animal {
public void showName() {
System.out.println(name);
eat();
}
}
The protected field and public method are accessible
to the subclass under Java's access rules. The private method is not directly accessible
from Dog. Private implementation details remain owned by the declaring class.
Inheritance Represents an "Is-a" Relationship
A good inheritance relationship should represent a genuine "is-a" relationship.
Natural Relationship
A Dog is an Animal.
class Dog extends Animal
Not an Inheritance Relationship
A Car has an Engine. A Car is not an Engine.
class Car {
private Engine engine;
}
When the relationship is primarily "has-a", composition is usually more appropriate than inheritance.
Method Overriding
Method overriding occurs when a subclass provides its own implementation of an inherited instance method. The child method uses the same method signature as the method being overridden.
class Animal {
public void sound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
The @Override annotation tells the compiler that
the method is intended to override an inherited method. It also helps catch mistakes
such as accidentally using the wrong method signature.
Runtime Polymorphism
One of the most important uses of method overriding is runtime polymorphism. A superclass reference can point to a subclass object. When an overridden instance method is called, Java uses the actual object's implementation.
class Animal {
public void sound() {
System.out.println("Some animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
Animal animal = new Dog();
animal.sound(); // Bark
The reference variable has type Animal,
but the object created at runtime is a Dog.
Therefore, the overridden Dog implementation runs.
Overloading vs Overriding
These two concepts are frequently confused, but they describe different mechanisms.
| Method Overloading | Method Overriding |
|---|---|
| Same method name with different parameter lists. | Subclass provides a new implementation of an inherited instance method. |
| Commonly used within the same class. | Requires an inheritance relationship. |
| Resolved using compile-time method selection. | Supports runtime polymorphic dispatch. |
Using super
The super keyword refers to the immediate superclass.
It is commonly used to call a superclass constructor, access a superclass member,
or invoke an overridden superclass method.
Calling a Parent Method
class Animal {
public void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
super.sound();
System.out.println("Dog bark");
}
}
Here, super.sound() explicitly calls the superclass
implementation before the Dog adds its own behavior.
Accessing a Superclass Field
class Animal {
protected String name = "Animal";
}
class Dog extends Animal {
private String name = "Dog";
public void printNames() {
System.out.println(name);
System.out.println(super.name);
}
}
The unqualified name refers to the Dog field,
while super.name explicitly refers to the
inherited field declared by Animal.
Calling a Superclass Constructor
A subclass constructor can invoke a superclass constructor using
super(...).
This call must appear as the first statement in the constructor.
class Person {
protected String name;
public Person(String name) {
this.name = name;
}
}
class Student extends Person {
private int age;
public Student(String name, int age) {
super(name);
this.age = age;
}
}
The Student constructor first initializes the inherited Person state and then initializes the fields belonging to Student.
Constructor Behavior During Inheritance
Constructors are not inherited like ordinary methods. However, when a subclass object is created, superclass construction is part of the object initialization process.
class Parent {
public Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
The superclass constructor executes as part of creating the child object before the child constructor body completes its own initialization work.
Constructor Chaining with super
When the parent class provides parameterized constructors, the child can use
super(...) to select the appropriate parent constructor.
class Employee {
protected String name;
protected double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
class Developer extends Employee {
private String language;
public Developer(
String name,
double salary,
String language
) {
super(name, salary);
this.language = language;
}
}
This keeps the initialization responsibility for Employee fields inside the Employee constructor instead of duplicating that logic in Developer.
Rules for Method Overriding
When overriding an inherited instance method, several Java rules apply. The child method must represent a valid override of the inherited method rather than simply defining an unrelated method with a similar name.
- The overriding method must have a compatible method signature.
- The return type must be the same or a valid covariant return type.
- The overriding method cannot reduce the accessibility of the inherited method.
- A method declared final cannot be overridden.
- Static methods are hidden rather than overridden.
- Private methods are not overridden because they are not accessible to subclasses.
- The @Override annotation is recommended for clarity and compiler checking.
Covariant Return Types
An overriding method can return a subtype of the return type used by the parent method. This is called a covariant return type.
class Animal {
public Animal create() {
return new Animal();
}
}
class Dog extends Animal {
@Override
public Dog create() {
return new Dog();
}
}
Dog is a subtype of Animal, so the overriding method can return Dog where the parent method returns Animal.
final and Inheritance
The final keyword can be used to prevent
a method from being overridden.
class Animal {
public final void breathe() {
System.out.println("Breathing");
}
}
A child class can inherit the method, but it cannot provide another implementation of that final method.
A class itself can also be declared final,
which prevents other classes from extending it.
final class Utility {
}
Static Methods and Inheritance
Static methods are associated with the class rather than with a particular object. They are not dynamically overridden in the same way as instance methods. If a subclass declares a static method with the same signature, the method is hidden.
class Parent {
public static void show() {
System.out.println("Parent");
}
}
class Child extends Parent {
public static void show() {
System.out.println("Child");
}
}
public class Main {
public static void main(String[] args) {
Parent.show();
Child.show();
}
}
This behavior is different from overriding instance methods and is an important distinction when reasoning about inheritance.
Protected Members
The protected access level is often encountered
in inheritance examples. It allows access within the same package and also provides
access to subclasses under Java's inheritance rules.
class Vehicle {
protected int speed;
}
class Car extends Vehicle {
public void accelerate() {
speed += 10;
}
}
Although protected members can be useful, they should not automatically be preferred over private state. In many designs, keeping fields private and exposing well-defined behavior through methods provides stronger encapsulation.
Upcasting
Assigning a child object to a parent reference is known as upcasting. It is a natural part of polymorphism.
Dog dog = new Dog();
Animal animal = dog;
animal.sound();
Through the Animal reference, you can access members available through the Animal type. When an overridden instance method is called, the actual Dog object's implementation is used.
Downcasting
A parent reference can sometimes be explicitly cast back to a child type. This is called downcasting and should only be performed when the object is actually an instance of the target child type.
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark();
}
Casting an object to an unrelated or incorrect subtype can result in a
ClassCastException.
Prefer designing APIs around common abstractions instead of relying heavily on
downcasting.
Multilevel Inheritance
Java allows a class to extend another class that itself extends a superclass. This creates a multilevel inheritance chain.
class Animal {
public void eat() {
System.out.println("Eating");
}
}
class Mammal extends Animal {
public void walk() {
System.out.println("Walking");
}
}
class Dog extends Mammal {
public void bark() {
System.out.println("Barking");
}
}
A Dog can use behavior inherited through the hierarchy:
Dog dog = new Dog();
dog.eat();
dog.walk();
dog.bark();
Although this is valid Java, very deep inheritance hierarchies can make behavior harder to understand. Keep inheritance structures as simple as the domain requires.
Java Does Not Support Multiple Class Inheritance
A Java class can extend one class directly. It cannot extend multiple classes at the same time.
// Not valid Java
class SmartPhone extends Phone, Camera {
}
Java uses interfaces to support multiple type contracts without allowing a class to inherit implementation from multiple class hierarchies in this way.
Inheritance Through a Practical Example
Consider a simple employee system. Different employees may share a name and salary, while each specialized employee can provide additional behavior.
class Employee {
protected String name;
protected double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public void work() {
System.out.println(name + " is working");
}
}
class Developer extends Employee {
private String language;
public Developer(
String name,
double salary,
String language
) {
super(name, salary);
this.language = language;
}
@Override
public void work() {
System.out.println(
name + " is developing with " + language
);
}
}
class Designer extends Employee {
public Designer(String name, double salary) {
super(name, salary);
}
@Override
public void work() {
System.out.println(name + " is designing");
}
}
The parent class contains shared information and behavior.
Developer and Designer specialize the common work()
operation by overriding it.
Polymorphic Collection of Child Objects
A common benefit of inheritance and overriding is that multiple child objects can be processed through a parent type.
Employee[] employees = {
new Developer("Alice", 70000, "Java"),
new Designer("Bob", 65000)
};
for (Employee employee : employees) {
employee.work();
}
The loop does not need separate logic for Developer and Designer.
It works with the shared Employee abstraction, while each object's overridden
work() method provides its specific behavior.
When Inheritance Is a Good Choice
Inheritance can be appropriate when a child type genuinely represents a specialized form of the parent type and should participate in the parent's abstraction.
- There is a meaningful "is-a" relationship.
- The child should be usable where the parent type is expected.
- Shared behavior is conceptually part of the parent abstraction.
- The child needs to specialize or extend the parent's behavior.
When Composition May Be Better
Inheritance is not automatically the best solution for code reuse. When an object depends on another object rather than being a specialized version of it, composition often produces a more flexible design.
class Engine {
public void start() {
System.out.println("Engine started");
}
}
class Car {
private final Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
public void start() {
engine.start();
System.out.println("Car started");
}
}
A Car contains an Engine rather than extending Engine. This keeps the relationship explicit and allows the Engine implementation to be replaced more easily.
Common Inheritance Mistakes
Using Inheritance Only for Code Reuse
Shared code does not automatically mean two classes should have an inheritance relationship. The domain relationship should make sense first.
Forgetting @Override
The annotation helps the compiler verify that the method actually overrides an inherited method and makes the developer's intent clear.
Confusing Overloading with Overriding
Overloading changes the parameter list, while overriding replaces inherited instance behavior in a subclass.
Trying to Override private or final Methods
Private methods are not inherited as overridable methods, and final methods cannot be overridden.
Confusing Static Method Hiding with Overriding
Static methods belong to classes and are hidden rather than dynamically overridden.
Creating Deep Inheritance Trees
Large hierarchies make it harder to understand where behavior comes from. Keep inheritance structures focused and avoid unnecessary levels.
Overusing Downcasting
Frequent casts from parent types back to child types can indicate that the abstraction is not exposing the behavior the application actually needs.
Inheritance Design Checklist
- Does the child genuinely represent a specialized form of the parent?
- Can a child object reasonably be used wherever the parent is expected?
- Does the parent contain behavior that belongs to the whole hierarchy?
- Are common methods designed around meaningful abstractions?
- Are subclass-specific responsibilities kept inside the subclass?
- Would composition communicate the relationship more accurately?
- Is the inheritance hierarchy shallow and understandable?
Inheritance and Polymorphism Flow
Parent Class
|
extends
|
v
Child Class
|
overrides method
|
v
Parent reference
|
v
Child object
|
v
Child implementation
runs at runtime
This flow is the key idea behind runtime polymorphism in Java: the reference type determines what members are available through the reference, while an overridden instance method can dispatch to the actual object's implementation.
Java Inheritance: Key Takeaways
- Inheritance allows one class to extend another using the extends keyword.
- The extending class is the child or subclass, and the extended class is the parent or superclass.
- Accessible inherited members can be used by subclasses according to Java's access rules.
- Private implementation details are not directly accessible to subclasses.
- Constructors are not inherited, but superclass construction is part of subclass object initialization.
- The super keyword can call a superclass constructor or access superclass behavior and members.
- Method overriding allows a subclass to provide specialized behavior.
- @Override helps the compiler verify an intended override.
- Overridden instance methods support runtime polymorphism.
- Static methods are hidden rather than overridden.
- Final methods cannot be overridden.
- Java supports single class inheritance and uses interfaces for multiple type contracts.
- Inheritance should represent a meaningful "is-a" relationship.
- Composition is often better for "has-a" relationships.
Summary
Java inheritance allows a child class to build on an existing parent class.
The extends keyword creates the relationship,
while access modifiers determine which inherited members are available.
Constructors are not inherited, but superclass constructors participate in creating
subclass objects, often through the super() call.
Method overriding allows subclasses to replace inherited instance behavior with a more specialized implementation. Combined with a parent reference pointing to a child object, overriding provides runtime polymorphism.
The most important design decision is knowing when inheritance actually represents the domain. Use it for genuine "is-a" relationships, avoid deep and unnecessary hierarchies, and consider composition when one object simply contains or depends on another.