Java MCQ: What is Inheritance in Java programming?
Answer:
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.