What is a subclass in Java inheritance?

Java MCQ: What is a subclass in Java inheritance?

A. The class that inherits from another class
B. The class that is inherited from
C. The final class in the inheritance chain
D. None of the above

Answer:

A. The class that inherits from another class

Explanation:

A subclass, also known as a derived class or child class, is a class that inherits properties (fields) and behaviors (methods) from another class, referred to as the superclass or parent class. Inheritance in Java allows the subclass to utilize and extend the functionality provided by the superclass. This promotes code reuse and establishes a hierarchical relationship between classes.

For example, consider the following code:


class Vehicle {
    int speed;
    void displaySpeed() {
        System.out.println("Speed: " + speed);
    }
}

class Car extends Vehicle {
    int numDoors;
    void displayCarInfo() {
        System.out.println("Number of doors: " + numDoors);
    }
}

Here, Car is a subclass of Vehicle. It inherits the speed field and the displaySpeed() method from the Vehicle class while also introducing its own field numDoors and method displayCarInfo(). This enables the Car class to perform actions defined in the superclass as well as its specific actions.

Subclasses can also override methods of the superclass to provide specific implementations. This is a key aspect of polymorphism, where the same method can behave differently depending on the subclass that implements it. By understanding how subclasses work, developers can create more modular, maintainable, and scalable Java applications.

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