Java Inheritance
Learn how to create new classes from existing ones, reuse code efficiently, and build powerful object-oriented applications.
What is Inheritance?
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) where one class acquires the properties (variables) and behaviors (methods) of another class. Think of it like a child inheriting traits from their parents!
The class that gives its properties is called the Parent Class (or Super Class/Base Class), and the class that receives those properties is called the Child Class (or Sub Class/Derived Class).
- Code Reusability: Write code once in the parent class and reuse it in child classes
- Method Overriding: Child classes can provide their own implementation of parent methods
- Extensibility: Easily add new features by creating child classes
Real-Life Example: A "Vehicle" is a general concept with properties like speed and color. A "Car" is a specific type of Vehicle that inherits these properties but adds its own features like number of doors. A "Bike" is another type of Vehicle with different specific features.
Inheritance Syntax
In Java, we use the extends keyword to inherit from a parent class. Here's the basic syntax:
Syntax: Inheritance in Java
class ParentClass {
// Parent class members
}
class ChildClass extends ParentClass {
// Child class members
// Inherits all members from ParentClass
}
Key Points:
- Use the
extendskeyword to create inheritance relationship - Child class automatically gets all public and protected members of parent class
- Private members of parent class are not directly accessible in child class
Simple Inheritance Example
Let's create a simple example where a Dog class inherits from an Animal class.
Example: Animal and Dog Classes
// Parent Class
class Animal {
String name;
void eat() {
System.out.println(name + " is eating");
}
void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child Class
class Dog extends Animal {
void bark() {
System.out.println(name + " is barking: Woof! Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Buddy";
// Calling inherited methods
myDog.eat();
myDog.sleep();
// Calling Dog's own method
myDog.bark();
}
}
Buddy is eating Buddy is sleeping Buddy is barking: Woof! Woof!
Explanation:
Dog extends Animal- Dog inherits all properties and methods from Animal- Dog can use
namevariable,eat(), andsleep()from Animal class - Dog also has its own method
bark()that Animal doesn't have - This demonstrates code reusability - we didn't rewrite eat() and sleep() in Dog class
Types of Inheritance in Java
1. Single Inheritance
When a class inherits from only one parent class. This is the most common and simplest form of inheritance.
Examples: Dog extends Animal, Car extends Vehicle, Student extends Person
2. Multilevel Inheritance
When a class is derived from another derived class, creating a chain of inheritance. Class C inherits from Class B, which inherits from Class A.
Examples: GrandChild extends Child extends Parent, Puppy extends Dog extends Animal
3. Hierarchical Inheritance
When multiple classes inherit from the same parent class. Multiple child classes share one parent.
Examples: Dog, Cat, and Bird all extend Animal; Circle, Rectangle, and Triangle all extend Shape
Important Note: Java does NOT support multiple inheritance (one class extending multiple classes) to avoid complexity and ambiguity. However, you can achieve similar functionality using interfaces!
Single Inheritance Example
A straightforward example where one class inherits from another class.
Example: Employee Inherits from Person
class Person {
String name;
int age;
void displayPersonInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Employee extends Person {
int employeeId;
double salary;
void displayEmployeeInfo() {
displayPersonInfo(); // Calling parent method
System.out.println("Employee ID: " + employeeId);
System.out.println("Salary: $" + salary);
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.name = "John Smith";
emp.age = 30;
emp.employeeId = 12345;
emp.salary = 50000;
emp.displayEmployeeInfo();
}
}
Name: John Smith Age: 30 Employee ID: 12345 Salary: $50000.0
Explanation:
- Employee class inherits name and age from Person class
- Employee adds its own properties: employeeId and salary
- Employee can call parent's displayPersonInfo() method directly
- This shows how child class extends parent functionality
Multilevel Inheritance Example
Creating a chain of inheritance where a class inherits from another derived class.
Example: Three-Level Inheritance Chain
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 myPuppy = new Puppy();
myPuppy.eat(); // From Animal class
myPuppy.bark(); // From Dog class
myPuppy.weep(); // From Puppy class
}
}
This animal eats food Dog barks Puppy weeps
Explanation:
- Puppy inherits from Dog, which inherits from Animal
- Puppy has access to methods from both Dog and Animal classes
- This creates a hierarchy: Animal → Dog → Puppy
- Each level adds more specific functionality
Hierarchical Inheritance Example
Multiple classes inheriting from the same parent class, creating a tree-like structure.
Example: Multiple Children from One Parent
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void drawCircle() {
System.out.println("Drawing a Circle");
}
}
class Rectangle extends Shape {
void drawRectangle() {
System.out.println("Drawing a Rectangle");
}
}
class Triangle extends Shape {
void drawTriangle() {
System.out.println("Drawing a Triangle");
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
Rectangle r = new Rectangle();
Triangle t = new Triangle();
c.draw();
c.drawCircle();
r.draw();
r.drawRectangle();
t.draw();
t.drawTriangle();
}
}
Drawing a shape Drawing a Circle Drawing a shape Drawing a Rectangle Drawing a shape Drawing a Triangle
Explanation:
- Circle, Rectangle, and Triangle all inherit from Shape
- All three child classes share the draw() method from Shape
- Each child class has its own specific method
- This allows different classes to share common functionality
The super Keyword
The super keyword is used to refer to the parent class. It's helpful for accessing parent class methods and constructors.
Example: Using super Keyword
class Vehicle {
int speed = 50;
void display() {
System.out.println("Vehicle speed: " + speed);
}
}
class Car extends Vehicle {
int speed = 100;
void display() {
System.out.println("Car speed: " + speed);
System.out.println("Vehicle speed: " + super.speed);
super.display(); // Calling parent's display method
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.display();
}
}
Car speed: 100 Vehicle speed: 50 Vehicle speed: 50
Explanation:
super.speedaccesses the parent class variablesuper.display()calls the parent class method- This is useful when child and parent have members with same names
- super helps avoid confusion between parent and child class members
Benefits of Inheritance
- Code Reusability: Write once, use multiple times in different child classes
- Method Overriding: Child classes can provide specific implementations of parent methods
- Extensibility: Easy to add new features by creating new child classes
- Data Hiding: Parent class can hide certain data from child classes using private access
- Polymorphism: Enables runtime polymorphism through method overriding
Best Practice: Use inheritance when there's a clear "is-a" relationship. A Dog IS-A Animal, A Car IS-A Vehicle. Don't force inheritance just for code reuse - consider composition as an alternative!
Important Rules
- Single Parent Only: A class can extend only one class in Java (no multiple inheritance)
- Constructor Chain: When creating a child object, parent constructor is called first
- Private Members: Private members of parent class cannot be accessed directly in child class
- final Class: A class declared as final cannot be inherited
- Object Class: Every class in Java automatically inherits from Object class
Remember: Inheritance represents "is-a" relationship. If you can say "Child IS-A Parent" naturally, inheritance is appropriate. For example: "Dog is an Animal" ✓, but "Car has an Engine" ✗ (use composition instead).