What is Inheritance in Java programming?

Java MCQ: What is Inheritance in Java programming?

A. It’s a process where one class acquires the properties (fields) and behaviors (methods) of another class.
B. It’s a process of creating a new class using the main() method.
C. It’s a technique to create objects in Java.
D. It’s a Java-specific term for importing packages.

Answer:

A. It’s a process where one class acquires the properties (fields) and behaviors (methods) of another class.

Explanation:

Inheritance is a fundamental concept in Java and Object-Oriented Programming (OOP) that allows a new class, known as a subclass, to inherit fields and methods from an existing class, referred to as the superclass. This mechanism provides several key benefits, such as code reusability, method overriding, and a clearer, more hierarchical structure in code design.

For example, consider a superclass Vehicle with common properties like speed and color. A subclass Car can inherit these properties and also introduce new ones, such as numDoors. This avoids the need to write redundant code, as Car automatically gains the properties and methods defined in Vehicle:


class Vehicle {
    int speed;
    String color;

    void displayInfo() {
        System.out.println("Speed: " + speed + " Color: " + color);
    }
}

class Car extends Vehicle {
    int numDoors;

    void displayCarInfo() {
        System.out.println("Number of doors: " + numDoors);
    }
}

In this example, the Car class inherits the speed and color fields from the Vehicle class, along with the displayInfo() method. This ability to extend classes and reuse code makes inheritance a powerful feature in Java.

Inheritance also plays a crucial role in polymorphism, another OOP principle, where a subclass can override methods of the superclass to provide specific implementations. By leveraging inheritance, Java developers can create more modular, maintainable, and scalable code.

Reference links:

https://www.javaguides.net/p/java-inheritance-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top