Understanding Inheritance in Java Basics
Q: What is inheritance in Java and how does it work?
- Java
- Mid level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and behaviors from another class. In Java, a subclass can inherit fields, methods, and inner classes from a superclass, which is achieved through the use of the `extends` keyword.
To illustrate how inheritance works in Java, consider the following example:
class Animal { protected int age; public Animal(int age) { this.age = age; } public void makeSound() { System.out.println("The animal makes a sound"); } } class Dog extends Animal { public Dog(int age) { super(age); } public void makeSound() { System.out.println("The dog barks"); } public void playFetch() { System.out.println("The dog plays fetch"); } }
In this example, `Animal` is the superclass and `Dog` is the subclass. The `Dog` class extends the `Animal` class by using the `extends` keyword, and inherits the `age` field and the `makeSound()` method from the `Animal` class.
The `Dog` class also has its own method called `playFetch()`, which is not present in the `Animal` class. This illustrates one of the benefits of inheritance: subclasses can add new functionality without having to duplicate code that is already present in the superclass.
To create an object of the `Dog` class, we can use the following code:
Dog myDog = new Dog(3);
This creates a new `Dog` object and initializes its `age` field to 3. Because the `Dog` class is a subclass of the `Animal` class, we can call the `makeSound()` method on the `myDog` object:
myDog.makeSound(); // prints "The dog barks"
This calls the `makeSound()` method of the `Dog` class, which overrides the `makeSound()` method of the `Animal` class.
In summary, inheritance in Java allows subclasses to inherit properties and behaviors from their superclass, and to add new functionality as needed. This helps to reduce code duplication and makes it easier to maintain and extend large codebases.


