Java Inheritance is one of the most important Object-Oriented Programming (OOP) concepts that allows developers to create new classes based on existing classes. It promotes code reusability, improves maintainability, and reduces redundancy in Java applications. Inheritance helps developers build scalable, modular, and cleaner code structures for real-world applications like banking systems, e-commerce applications, school management tools, and enterprise software.In Java, inheritance enables a class to acquire the properties, methods, and behavior of another class. The class that inherits is known as the subclass or child class, and the class from which it inherits is known as the superclass or parent class. This concept lies at the heart of Javaβs flexibility and has a major role in constructing frameworks, libraries, and reusable modules.
Before diving deeper, it is essential to understand why inheritance is a core part of Java programming. Some key advantages include:
In Java, inheritance is implemented using the extends keyword. This keyword indicates that a class derives from another class.
class Parent {
// parent class code
}
class Child extends Parent {
// child class code
}
With this structure, the child class automatically receives access to all non-private fields and methods of the parent class.
Although Java does not support all types of inheritance directly, different forms are used widely in applications. Below are the major categories:
In single inheritance, one class inherits from one parent class. This is the simplest form of inheritance and is widely used in Java applications.
class Vehicle {
void startEngine() {
System.out.println("Engine started");
}
}
class Car extends Vehicle {
void carBrand() {
System.out.println("Brand: Toyota");
}
}
In multilevel inheritance, a class inherits from another class, and then another class inherits from that derived class. It forms a chain-like structure.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Mammal extends Animal {
void walk() {
System.out.println("Walking...");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("Barking...");
}
}
In hierarchical inheritance, multiple classes inherit from the same parent class. This is highly useful for creating large class hierarchies.
class Shape {
void draw() {
System.out.println("Drawing shape...");
}
}
class Circle extends Shape {
void area() {
System.out.println("Area of Circle");
}
}
class Rectangle extends Shape {
void area() {
System.out.println("Area of Rectangle");
}
}
Java does not support multiple inheritance using classes to avoid ambiguity problems such as the Diamond Problem. However, Java supports multiple inheritance using interfaces.
interface A {
void display();
}
interface B {
void show();
}
class Test implements A, B {
public void display() {
System.out.println("Display");
}
public void show() {
System.out.println("Show");
}
}
Hybrid inheritance is a combination of multiple inheritance types. Java does not support this directly using classes but supports it through interfaces.
A superclass (parent class) provides properties and methods that the subclass (child class) extends or inherits. The subclass can use the functionality of the parent class and can also introduce new behavior.
Access modifiers determine which members of a class can be inherited and accessed by child classes.
| Modifier | Inheritance Scope |
|---|---|
| public | Accessible everywhere, fully inheritable |
| protected | Accessible within same package and subclasses |
| default | Accessible only within same package |
| private | Not accessible or inheritable directly |
Constructors are not inherited, but the constructor of the parent class is automatically called when creating an object of the child class.
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
class Child extends Parent {
Child() {
System.out.println("Child Constructor");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
}
}
Output:
Parent Constructor
Child Constructor
The super keyword allows subclasses to refer to the superclass's fields, methods, and constructors.
class Parent {
void message() {
System.out.println("Message from Parent");
}
}
class Child extends Parent {
void message() {
super.message();
System.out.println("Message from Child");
}
}
class Parent {
Parent(String name) {
System.out.println("Parent: " + name);
}
}
class Child extends Parent {
Child() {
super("John");
System.out.println("Child Constructor");
}
}
Method overriding occurs when a subclass provides a specific implementation of a method already defined in its parent class. It supports runtime polymorphism.
class Bank {
int getRateOfInterest() {
return 5;
}
}
class SBI extends Bank {
int getRateOfInterest() {
return 8;
}
}
class ICICI extends Bank {
int getRateOfInterest() {
return 9;
}
}
Inheritance represents an IS-A relationship. Example: A Dog IS-A Animal, a Car IS-A Vehicle.
class Animal {}
class Dog extends Animal {}
HAS-A represents a class containing another class as a member, not inheritance.
class Engine {}
class Car {
Engine e = new Engine();
}
A final class cannot be inherited.
final class Vehicle {}
class Car extends Vehicle {} // Error!
A final method cannot be overridden.
class A {
final void display() {}
}
class B extends A {
void display() {} // Error!
}
A final variable cannot be changed once initialized.
class Person {
String name;
int age;
}
class Student extends Person {
int rollNo;
}
class Teacher extends Person {
double salary;
}
class Product {
String name;
double price;
}
class Electronics extends Product {
int warranty;
}
class Clothing extends Product {
String size;
}
Java Inheritance is a powerful feature that plays an essential role in building large-scale object-oriented applications. It enhances code reusability, promotes cleaner project structures, and supports OOP concepts like polymorphism and abstraction. Understanding inheritance is vital for beginners, intermediate learners, and advanced developers working on enterprise-level Java applications. Mastery of inheritance leads to better software design, improved efficiency, and high-quality coding skills.
Java is known for its key features such as object-oriented programming, platform independence, robust exception handling, multithreading capabilities, and automatic garbage collection.
The Java Development Kit (JDK) is a software development kit used to develop Java applications. The Java Runtime Environment (JRE) provides libraries and other resources to run Java applications, while the Java Virtual Machine (JVM) executes Java bytecode.
Java is a high-level, object-oriented programming language known for its platform independence. This means that Java programs can run on any device that has a Java Virtual Machine (JVM) installed, making it versatile across different operating systems.
Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting for each other to release resources.
Functional programming in Java involves writing code using functions, immutability, and higher-order functions, often utilizing features introduced in Java 8.
A process is an independent program in execution, while a thread is a lightweight subprocess that shares resources with other threads within the same process.
The Comparable interface defines a natural ordering for objects, while the Comparator interface defines an external ordering.
The List interface allows duplicate elements and maintains the order of insertion, while the Set interface does not allow duplicates and does not guarantee any specific order.
String is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable, allowing modifications to their contents. The main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not.
Checked exceptions are exceptions that must be either caught or declared in the method signature, while unchecked exceptions do not require explicit handling.
ArrayList is backed by a dynamic array, providing fast random access but slower insertions and deletions. LinkedList is backed by a doubly-linked list, offering faster insertions and deletions but slower random access.
Autoboxing is the automatic conversion between primitive types and their corresponding wrapper classes. For example, converting an int to Integer.
The 'synchronized' keyword in Java is used to control access to a method or block of code by multiple threads, ensuring that only one thread can execute it at a time.
Multithreading in Java allows concurrent execution of two or more threads, enabling efficient CPU utilization and improved application performance.
A HashMap is a collection class that implements the Map interface, storing key-value pairs. It allows null values and keys and provides constant-time performance for basic operations.
Java achieves platform independence by compiling source code into bytecode, which is executed by the JVM. This allows Java programs to run on any platform that has a compatible JVM.
The Serializable interface provides a default mechanism for serialization, while the Externalizable interface allows for custom serialization behavior.
The 'volatile' keyword in Java indicates that a variable's value will be modified by multiple threads, ensuring that the most up-to-date value is always visible.
Serialization is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network.
The finalize() method is called by the garbage collector before an object is destroyed, allowing for cleanup operations.
The 'final' keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes, ensuring that certain elements remain unchanged.
Garbage collection is the process by which the JVM automatically deletes objects that are no longer reachable, freeing up memory resources.
'throw' is used to explicitly throw an exception, while 'throws' is used in method declarations to specify that a method can throw one or more exceptions.
The 'super' keyword in Java refers to the immediate parent class and is used to access parent class methods, constructors, and variables.
The JVM is responsible for loading, verifying, and executing Java bytecode. It provides an abstraction between the compiled Java program and the underlying hardware, enabling platform independence.
Copyrights © 2024 letsupdateskills All rights reserved