Inheritance is a mechanism in Java that allows one class to inherit the properties and behaviors of another class. The class that inherits is called the child or subclass, and the class that is inherited from is called the parent or superclass.
Here’s an example to illustrate inheritance in Java:
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.eat(); // output: Buddy is eating.
dog.bark(); // output: Woof!
}
}
In this example, we have defined an Animal
class with a constructor that takes a name
parameter and an eat
method. We have also defined a Dog
class that extends Animal
and has a bark
method.
The Dog
class inherits the name
and eat
properties from the Animal
class, and adds the bark
behavior. When we create a Dog
object, we can call both the inherited eat
method and the bark
method.
Inheritance in Java provides several benefits, including code reuse, the ability to create specialized classes from existing ones, and polymorphism. By using inheritance, we can create a hierarchy of classes that represent the real-world relationships between objects.