Inheritance enables a class to reuse properties and behaviors of another class in Java.
Java inheritance promotes reusability and polymorphism, supporting single, multilevel, hierarchical inheritance and interfaces.
Inheritance in Java is a core concept in object-oriented programming (OOP) that enables a class (known as a subclass or derived class) to inherit properties and behaviors (fields and methods) from another class (known as a superclass or base class). This powerful feature helps developers build modular, readable, and reusable code. In simpler terms, when one class acquires the properties of another class, it's called Inheritance in Java program.
1. Code Reusability:
Subclasses reuse code from the superclass without rewriting it.
Example: Car class can reuse properties from Vehicle.
2. Modularity:
Java inheritance promotes a modular and structured approach.
Helps in breaking the problem into manageable pieces.
3. Polymorphism in Java:
Inherited classes can be used in a polymorphic way.
Supports Java polymorphism by allowing function overriding in Java.
4. Maintainability:
Inheritance allows easier updates and bug fixes.
Updating a method in the superclass reflects in all subclasses.
1. Single Inheritance in Java
Java supports single inheritance, where one class inherits from a single superclass.
// java single inheritance program
class Vehicle {
void start() {
System.out.println("Vehicle started.");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is being driven.");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.drive();
}
}
2. Multilevel Inheritance in Java
When a class inherits from another class, which itself inherits from another class.
// multilevel inheritance in java
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
class BullDog extends Dog {
void guard() {
System.out.println("Bulldog is guarding.");
}
}
3. Hierarchical Inheritance in Java
In this type, multiple subclasses inherit from a single superclass.
// hierarchical inheritance in java
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle.");
}
}
4. Multiple Inheritance in Java
Java does not support multiple inheritance through classes due to the diamond problem. However, it allows multiple inheritance via interfaces, a feature of interface inheritance in Java.
// difference between inheritance and interface in Java
interface Jumpable {
void jump();
}
interface Runnable {
void run();
}
class Athlete implements Jumpable, Runnable {
public void jump() {
System.out.println("Athlete jumps.");
}
public void run() {
System.out.println("Athlete runs.");
}
}
To define inheritance in Java, let’s use two classes:
Superclass: Person
Subclass: Player
Features Implemented:
Inheritance OOP Java principles
Polymorphism using function overriding in Java
// Person.java
public class Person {
private int id;
private String firstName, lastName;
private long contactNumber;
private static int generatedId = 100;
public Person(String firstName, String lastName, long contactNumber) {
this.id = ++generatedId;
this.firstName = firstName;
this.lastName = lastName;
this.contactNumber = contactNumber;
}
public String toString() {
return id + ", " + firstName + ", " + lastName + ", " + contactNumber;
}
}
// Player.java
public class Player extends Person {
private String game;
private int experience;
public Player(String firstName, String lastName, long contactNumber, String game, int experience) {
super(firstName, lastName, contactNumber);
this.game = game;
this.experience = experience;
}
public String calcPlayerType() {
if (experience < 1) return "Beginner";
else if (experience < 3) return "Intermediate";
else return "Expert";
}
public String toString() {
return "Player{" + super.toString() + ", game='" + game + "', experience=" + experience + ", Player Type=" + calcPlayerType() + "}";
}
}
Here, we extend the idea of super class in Java to build a financial system.
Superclass: Account
Fields: accountNumber, balance
Methods: deposit(), withdraw(), toString()
Subclass 1: SavingAccount
Adds interestRate and addInterest() method
Subclass 2: RecurringAccount
Adds monthlyDeposit and depositMonthly() method
// inheritance in java program
public class Account {
private String accountNumber;
private double balance;
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
}
// SavingAccount.java
public class SavingAccount extends Account {
private double interestRate;
public void addInterest() {
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
}
// RecurringAccount.java
public class RecurringAccount extends Account {
private double monthlyDeposit;
public void depositMonthly() {
deposit(monthlyDeposit);
}
}
Function Overloading:
Multiple methods with the same name but different parameters.
Function Overriding:
Subclass redefines the method from the superclass.
Supports runtime polymorphism.
Use Case 1: Shape Hierarchy
Implement Shape, Rectangle, and Circle to calculate area and perimeter.
Use Case 2: Vehicle Hierarchy
Use Vehicle, Car, and Truck to demonstrate inheritance types in Java and fuel efficiency.
Use Case 3: Library Management System
Create Item, Book, and DVD classes to calculate late fees.
Use Case 4: Bank Account Hierarchy
Extend Account to include SavingAccount and CheckingAccount. Demonstrate program inheritance Java.
Explain inheritance in Java clearly to understand how object-oriented principles work in Java. Whether it’s single inheritance, multilevel inheritance, or hierarchical inheritance in Java, this concept helps in structuring programs efficiently. If you aim to master inheritance OOP Java, consistent practice with real-life examples and use cases is crucial.
Want to implement these Java inheritance concepts in real-world applications or need expert guidance? Contact us now and take the next step in your learning journey!
📞 Call us: +91-8587000904, 8587000906, 9643424141
🌐 Visit: www.cyberinfomines.com
📧 Email: vidhya.chandel@cyberinfomines.com