Inheritance In Java
Inheritance is a concept in Java that allows one class to inherit the features and behaviors of another class. It is a way of creating new classes based on existing ones, and reusing the code and functionality of the parent class. Inheritance also enables polymorphism, which is the ability of an object to take different forms depending on the context.
There are different types of inheritance in Java, such as
- single,
- multilevel,
- hierarchical inheritance
1.Single inheritance is when a subclass inherits from only one superclass. 2.Multilevel inheritance is when a subclass inherits from another subclass, which in turn inherits from another superclass. 3.Hierarchical inheritance is when multiple subclasses inherit from the same superclass.
To implement inheritance in Java, you need to use the extends
keyword after the subclass name, followed by the superclass name. For example:
// A superclass called Animal
class Animal {
// A method that makes a sound
public void makeSound() {
System.out.println("Animal sound");
}
}
// A subclass called Dog that inherits from Animal
class Dog extends Animal {
// A method that overrides the makeSound() method of Animal
@Override
public void makeSound() {
System.out.println("Woof");
}
}
// A subclass called Cat that inherits from Animal
class Cat extends Animal {
// A method that overrides the makeSound() method of Animal
@Override
public void makeSound() {
System.out.println("Meow");
}
}
In this example, both Dog
and Cat
are subclasses of Animal
, and they inherit the makeSound()
method from Animal
. However, they also override the makeSound()
method to provide their own implementation, which is specific to their class. This is an example of method overriding, which is one of the benefits of inheritance.