What is Java Inheritance?
Inheritance is one of the fundamental concepts of Object-Oriented Programming (OOP) in Java. It allows a new class (called a child or subclass) to inherit properties and behaviors (fields and methods) from an existing class (called a parent or superclass).
Syntax of Java Inheritance.
The syntax for inheritance in Java involves creating a subclass that extends a superclass using the extends keyword. Here’s the basic structure:
Syntax: #
class Superclass {
// Fields (variables)
// Methods
}
class Subclass extends Superclass {
// Additional fields (variables)
// Additional methods or overriding methods
}
Types of Inheritance
1. Single Inheritance #
Definition: Single inheritance is where a subclass inherits from one superclass.
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Subclass-specific method
}
}
In this example, Dog inherits from Animal, and it can use the eat() method defined in Animal as well as its own bark() method.
2. Multilevel Inheritance
Definition: In multilevel inheritance, a class inherits from another class, which in turn inherits from another class, forming a chain.
Example:
// Base class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Intermediate class
class Mammal extends Animal {
void breathe() {
System.out.println("This mammal breathes air.");
}
}
// Derived class
class Dog extends Mammal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.breathe(); // Inherited from Mammal
myDog.bark(); // Dog-specific method
}
}
3. Hierarchical Inheritance #
Definition: In hierarchical inheritance, multiple subclasses inherit from a single superclass.
Example:
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();
myDog.eat(); // Inherited method
myDog.bark(); // Dog-specific method
myCat.eat(); // Inherited method
myCat.meow(); // Cat-specific method
}
}
In this example, both Dog and Cat inherit from Animal, but each has its own specific methods.