Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and methods from another class. The class that is being inherited from is called the superclass or base class, and the class that is inheriting is called the subclass or derived class.
In Java, inheritance is achieved using the extends
keyword. When a subclass extends a superclass, it inherits all of the properties and methods of the superclass, and can add new properties and methods or override existing ones as needed. Here’s an example of inheritance in Java:
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking");
}
public void makeSound() {
System.out.println("Dog is barking");
}
}
In this example, the Animal
class has two methods (eat()
and makeSound()
), which are inherited by the Dog
class using the extends
keyword. The Dog
class also has its own bark()
method, which is not present in the Animal
class. In addition, the Dog
class overrides the makeSound()
method from the Animal
class with its own implementation.
By using inheritance effectively, you can create more modular, reusable, and extensible code that is easier to maintain and modify. Inheritance allows you to avoid code duplication and promote code reuse by allowing subclasses to inherit and build upon the functionality of their superclasses.