Java MCQ: Which keyword is used for inheritance in Java?
Answer:
Explanation:
The extends
keyword in Java is used to indicate that a class is inheriting from another class. When a class is defined with the extends
keyword, it becomes a subclass (or child class) of the specified superclass (or parent class). This mechanism is a core part of Java’s object-oriented structure, allowing subclasses to inherit fields and methods from their superclass, enabling code reuse and the establishment of hierarchical relationships between classes.
For example, if you have a superclass Animal
and you want to create a subclass Dog
, you would use the extends
keyword as follows:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
In this example, Dog
inherits the eat()
method from Animal
and also defines its own method, bark()
. This allows Dog
objects to use both eat()
and bark()
methods, showcasing the power of inheritance.
The extends
keyword not only facilitates inheritance but also supports polymorphism, where a subclass can provide specific implementations of methods defined in its superclass. This is particularly useful in creating flexible and maintainable code, as it allows for the extension and modification of existing code without altering the original class structure.