Java MCQ: What is a subclass in Java inheritance?
Answer:
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.