Java Tutorial 38 of 143
Basics
- Introduction
- Download and Install Java
- Download and Install IntelliJ IDEA, Eclipse
- Creating First Java Application in IntelliJ IDEA
- JDK vs JRE vs JVM
- Print output
- Taking Input
- Identifiers
- Keywords
- Variables
- Data Types
- Literals
- Wrapper Classes
- Operators
- Decision Making
- Loops and Jump Statements
- Project: Number Guessing Game
Methods
- Introduction
- Static Methods vs Instance Methods
- Access Modifiers
- Command Line Arguments
- Variable Arguments (Varargs)
Arrays
- Introduction
- One Dimensional Arrays
- Multidimensional Arrays
- Array Class
- Arrays Class
Strings
- Introduction
- String
- StringBuffer
- StringBuilder
- String Class Methods
- StringJoiner
- StringTokenizer
OOP & Interface
- Introduction
- Java Constructors
- Java Encapsulation
- Inheritance
- Java Polymorphism
- Java Abstraction
- Interfaces
- this Keyword
- super Keyword
- static Keyword
- final Keyword
- Access Modifiers
- Nested Classes
- Anonymous Inner Class
Collections
- Collection class
- Collection Interface
- List Interface
- ArrayList
- LinkedList
- Set Interface
- HashSet
- LinkedHashSet
- TreeSet
- Queue Interface
- PriorityQueue
- Deque
- ArrayDeque
- Map Interface in Java
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
- Iterator
- Comparable and Comparator
Exception Handling
- Introduction
- Java Exception Handling
- Java Try-Catch
- Java Finally Block
- Java throw and throws
- Java Custom Exceptions
- Java Checked vs Unchecked Exceptions
Multithreading & Concurrency
- Introduction
- Thread Class
- Runnable Interface
- Thread Life Cycle
- Thread Priority
- Synchronization
- Inter-Thread Communication
- Executor Framework
- Callable and Future
- Concurrent Collections
Java 8 Features
- Lambda Expressions
- Functional Interfaces
- Method References
- Stream API
- Optional Class
- Default and Static Methods in Interface
- Date and Time API
Advanced Java Concepts
- File Handling
- Serialization and Deserialization
- Reflection API
- Annotations
- Garbage Collection
- Memory Management
- JVM Architecture
- Class Loading
- Networking
- Regular Expressions
JDBC
- Introduction
- JDBC Driver
- JDBC Connection
- Types of Statements in JDBC
- Transactions
- ResultSet
- Metadata
- Connection Pooling
Web & Enterprise
- Servlets
- JSP
- Spring Framework
- Spring Boot
- Hibernate
- REST API Development
Practice Projects
- Project: Number Guessing Game
- Project: Banking System
- Project: Student Management System
- Project: Library Management System
- Project: Quiz Application
Quiz and Coding Practice
- Java Topic-wise Quiz
- Coding Practice Problems
- Java Basics Coding Practice Problems
- Java Exercises
Interview Questions
- Core Java Interview Questions and Answers
- Advanced Java Interview Questions and Answers
- Java Interview Questions
DSA & Competitive Programming
- Arrays and Strings
- Linked List
- Stack
- Queue
- Tree
- Graph
- Heap
- Hashing
- Sorting
- Searching
- Dynamic Programming
- Roadmap for DSA in Java
Inheritance
Learn Java inheritance, including single, multilevel, and hierarchical inheritance, method overriding, super, and how inheritance supports code reuse and polymorphism.
On this page
- What Is Inheritance in Java?
- Why Use Inheritance?
- Types of Inheritance in Java
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance with Classes
- Multiple Inheritance Using Interfaces
- The super Keyword
- Accessing a Parent Field
- Calling a Parent Method
- Calling a Parent Constructor
- Method Overriding
- Inheritance and Polymorphism
- Inheritance and Access Modifiers
- final and Inheritance
- Final Class
- Final Method
- Object Class and Inheritance
- IS-A Relationship
- HAS-A Relationship
- Inheritance vs Composition
- Constructor Execution in Inheritance
- Advantages of Inheritance
- 1. Code Reuse
- 2. Reduced Duplication
- 3. Supports Polymorphism
Java Inheritance
Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in Java. It allows one class to acquire fields and methods from another class, helping developers reuse common functionality and build relationships between classes.
For example, a Dog is an Animal. Instead of defining common animal behavior again in the Dog class, the Dog class can inherit it from Animal.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
Now a Dog object can use both methods:
Dog dog = new Dog();
dog.eat();
dog.bark();
Output:
Animal is eating
Dog is barking
Here, Dog is the child class and Animal is the parent class.
What Is Inheritance in Java?
Inheritance is a mechanism through which a class derives properties and behavior from another class.
The class being inherited from is commonly called the:
- Parent class
- Superclass
- Base class
The class that inherits from it is called the:
- Child class
- Subclass
- Derived class
The extends keyword is used for class inheritance.
Syntax:
class ChildClass extends ParentClass {
// members
}
Example:
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
Why Use Inheritance?
Inheritance can provide several benefits:
- Code reuse
- Reduced duplication
- Easier maintenance
- Hierarchical organization of related classes
- Support for method overriding
- Support for runtime polymorphism
For example, multiple vehicle types may share common behavior:
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
void stop() {
System.out.println("Vehicle stopped");
}
}
Different vehicle classes can reuse this functionality:
class Car extends Vehicle {
}
class Bike extends Vehicle {
}
Both classes can use start() and stop() without redefining them.
Types of Inheritance in Java
Java supports several inheritance structures using classes.
The commonly discussed types are:
- Single inheritance
- Multilevel inheritance
- Hierarchical inheritance
Java does not support multiple inheritance of classes.
Multiple inheritance can be achieved through interfaces.
Single Inheritance
In single inheritance, one child class inherits from one parent class.
Structure:
Parent
|
Child
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
Usage:
Dog dog = new Dog();
dog.eat();
dog.bark();
The Dog class inherits from Animal.
Multilevel Inheritance
In multilevel inheritance, a class inherits from another child class, creating a chain.
Structure:
Animal
|
Mammal
|
Dog
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Mammal extends Animal {
void breathe() {
System.out.println("Breathing");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("Barking");
}
}
Now Dog can access methods from both Mammal and Animal:
Dog dog = new Dog();
dog.eat();
dog.breathe();
dog.bark();
Output:
Eating
Breathing
Barking
Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from the same parent class.
Structure:
Vehicle
/ \
Car Bike
Example:
class Vehicle {
void start() {
System.out.println("Vehicle started");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
class Bike extends Vehicle {
void ride() {
System.out.println("Bike is riding");
}
}
Both Car and Bike inherit start() from Vehicle.
Car car = new Car();
car.start();
car.drive();
Bike bike = new Bike();
bike.start();
bike.ride();
Multiple Inheritance with Classes
Java does not allow a class to extend multiple classes.
The following is invalid:
class A {
}
class B {
}
class C extends A, B {
}
This is not supported because it can create ambiguity when both parent classes contain methods with the same signature.
Java instead uses interfaces to support multiple inheritance of type.
Multiple Inheritance Using Interfaces
A class can implement multiple interfaces.
interface Printable {
void print();
}
interface Scannable {
void scan();
}
class Printer implements Printable, Scannable {
public void print() {
System.out.println("Printing");
}
public void scan() {
System.out.println("Scanning");
}
}
Now Printer follows both contracts.
Printer printer = new Printer();
printer.print();
printer.scan();
This provides a way to combine capabilities without extending multiple classes.
The super Keyword
The super keyword refers to the immediate parent class.
It can be used to:
- Access a parent class field
- Call a parent class method
- Call a parent class constructor
Accessing a Parent Field
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println(name);
System.out.println(super.name);
}
}
Output:
Dog
Animal
name refers to the child field, while super.name refers to the parent field.
Calling a Parent Method
A child class can override a parent method and still call the parent implementation using super.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound();
System.out.println("Dog barks");
}
}
Calling:
Dog dog = new Dog();
dog.sound();
Output:
Animal makes a sound
Dog barks
Calling a Parent Constructor
The super() call invokes the constructor of the parent class.
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("Dog constructor");
}
}
Creating the object:
Dog dog = new Dog();
Output:
Animal constructor
Dog constructor
If a child constructor does not explicitly call a parent constructor, Java implicitly attempts to call the accessible no-argument parent constructor.
Method Overriding
Inheritance allows a child class to provide its own implementation of a method inherited from the parent class.
This is called method overriding.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Now:
Dog dog = new Dog();
dog.sound();
Output:
Dog barks
The Dog implementation overrides the inherited Animal implementation.
The @Override annotation is recommended because it allows the compiler to verify that the method is actually overriding a parent method.
Inheritance and Polymorphism
Inheritance is closely related to polymorphism.
A parent-class reference can refer to an object of a child class.
Animal animal = new Dog();
animal.sound();
If Dog overrides sound(), the Dog implementation is executed at runtime.
Example:
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}
Output:
Dog barks
This is an example of runtime polymorphism.
Inheritance and Access Modifiers
Not every member of a parent class is directly accessible from a child class.
For example:
class Parent {
private int privateValue = 10;
protected int protectedValue = 20;
public int publicValue = 30;
}
A child class can directly access the protected and public members, subject to Java's access rules, but cannot directly access the private field.
class Child extends Parent {
void display() {
// System.out.println(privateValue); // Not allowed
System.out.println(protectedValue);
System.out.println(publicValue);
}
}
Private members still belong to the parent object's state, but they are not directly accessible from the child class.
final and Inheritance
The final keyword can restrict inheritance and overriding.
Final Class
A final class cannot be extended.
final class Vehicle {
}
This is invalid:
class Car extends Vehicle {
}
Final Method
A final method cannot be overridden.
class Animal {
final void eat() {
System.out.println("Eating");
}
}
The child class cannot override eat().
class Dog extends Animal {
// Cannot override final method
}
Object Class and Inheritance
Every Java class ultimately inherits from java.lang.Object, directly or indirectly.
For example:
class Animal {
}
Animal implicitly extends Object.
Therefore:
class Dog extends Animal {
}
has an inheritance chain similar to:
Object
|
Animal
|
Dog
Methods such as toString(), equals(), and hashCode() originate from Object and can be overridden when appropriate.
IS-A Relationship
Inheritance represents an IS-A relationship.
For example:
Dog IS-A Animal
Car IS-A Vehicle
Manager IS-A Employee
In Java:
class Dog extends Animal {
}
This expresses that a Dog is an Animal.
Inheritance should generally represent a meaningful subtype relationship rather than simply being used to reuse unrelated code.
HAS-A Relationship
A HAS-A relationship is usually represented using composition rather than inheritance.
For example:
Car HAS-A Engine
Example:
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine = new Engine();
void startCar() {
engine.start();
}
}
Here, Car contains an Engine.
This is composition, not inheritance.
Inheritance vs Composition
| Inheritance | Composition |
|---|---|
| Represents an IS-A relationship | Represents a HAS-A relationship |
Uses extends |
Uses object references |
| Creates a class hierarchy | Combines objects |
| Can provide inherited behavior | Delegates behavior to contained objects |
| Creates stronger coupling between parent and child | Often provides more flexibility |
For example:
class Dog extends Animal {
}
represents an IS-A relationship.
Whereas:
class Car {
private Engine engine;
}
represents a HAS-A relationship.
Constructor Execution in Inheritance
When a child object is created, the parent constructor executes before the child constructor.
Example:
class A {
A() {
System.out.println("A");
}
}
class B extends A {
B() {
System.out.println("B");
}
}
class C extends B {
C() {
System.out.println("C");
}
}
Creating:
C object = new C();
produces:
A
B
C
The initialization proceeds from the top of the inheritance hierarchy toward the child class.
Advantages of Inheritance
1. Code Reuse
Common functionality can be defined once in a parent class.
2. Reduced Duplication
Child classes can reuse inherited methods instead of implementing the same code repeatedly.
3. Supports Polymorphism
Parent references can represent
Related
-
Java Constructors
Learn Java constructors, including default and parameterized constructors, constructor overloading, chaining, and how constructors initialize objects.
-
Java Polymorphism
Learn Java polymorphism, including compile-time and runtime polymorphism, method overloading, method overriding, dynamic method dispatch, and practical examples.
-
Java Encapsulation
Learn Java encapsulation, how to protect object data using access modifiers, getters and setters, and why encapsulation improves code security and maintainability.
-
Java Abstraction
Learn Java abstraction using abstract classes and interfaces to hide implementation details, define common behavior, and build flexible object-oriented applications.