Java Inheritance
Introduction to Inheritance in Java
Inheritance is a key principle of Object-Oriented Programming (OOP) in Java. This fundamental concept allows us to create new classes using existing classes. The goal of inheritance is to promote the reuse of code, simplify the creation of related classes, and establish a type hierarchy for objects.
What is Inheritance?
Inheritance in Java is a mechanism where a new class is derived from an existing class. The existing class is known as the superclass
or parent class
, and the newly created class is referred to as the subclass
or child class
.
The child class inherits all the states (attributes) and behaviors (methods) of the parent class, and can also add its own unique states and behaviors.
Syntax of Inheritance
In Java, the extends
keyword is used to establish inheritance relationship between two classes. Here's a basic syntax of how to use it:
class Subclass extends Superclass{
// fields and methods
}
In the above syntax, Subclass
is the new class we're creating (child class), and Superclass
is the existing class from which we're inheriting (parent class).
Example of Inheritance
Let's illustrate inheritance with a simple example. Suppose we have a superclass Animal
and a subclass Dog
.
class Animal {
void eat() {
System.out.println("The animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
In this example, Dog
class inherits the eat()
method from Animal
class. Now, we can create an object of Dog
class and call both eat()
and bark()
methods.
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
When you run the program, you'll see this output:
The animal eats
The dog barks
This shows that the Dog
class has successfully inherited from the Animal
class.
Types of Inheritance
Java supports four types of inheritance:
- Single Inheritance: When a class extends another single class.
- Multilevel Inheritance: When a class extends a class, which extends another class.
- Hierarchical Inheritance: When a single class is extended by multiple classes.
- Hybrid Inheritance: A combination of more than one types of inheritance.
Note: Java does not support multiple inheritance (a class extending more than one classes) because it leads to ambiguity.
Conclusion
Inheritance is a powerful feature in Java, it helps to reduce code redundancy and makes your code modular. It's a crucial part of Java's OOP model. As you progress, you'll see how inheritance plays a vital role in other OOP concepts like polymorphism and abstraction.
Remember, practice is the key to mastering any concept, so try creating your own classes and experimenting with inheritance.
Happy Coding!