Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit properties and behaviors from another class. In Java, inheritance is achieved using the extends keyword. The class that is being inherited from is called the superclass, while the class that is inheriting from the superclass is called the subclass.
Here is an example of inheritance in Java:
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " says hello!");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println(getName() + " says woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog fido = new Dog("Fido");
fido.speak();
fido.bark();
}
}
In this example, we have an Animal class with a constructor that takes a name as a parameter and a speak() method that prints a message to the console. We also have a Dog subclass that extends the Animal class and adds a bark() method that also prints a message to the console.
When we create a new Dog object named fido in the Main class, we pass the name "Fido" to the Dog constructor. We can then call the speak() method on fido, which is inherited from the Animal class, as well as the bark() method that is specific to the Dog class.
The output of running this program would be:
Fido says hello!
Fido says woof!
In summary, inheritance is a powerful feature in Java that allows subclasses to inherit properties and behaviors from a superclass. This can help to reduce code duplication and make code more modular and reusable.