Java, being an object-oriented programming language, supports inheritance which is a fundamental concept allowing one class to acquire the properties and methods of another class. The keyword which makes this possible in Java is extends
.
The extends
keyword is used to signify that one class (sub-class or child class) is inheriting properties and methods from another class (super-class or parent class).
Here's a basic syntax of how extends
is used in Java:
class SubClass extends SuperClass {
// body of the class
}
In this example, SubClass
is inheriting the properties and methods of SuperClass
using the extends
keyword.
Let's illustrate this with a practical example. Imagine a super-class Animal
that has a method eat()
. We create a sub-class Dog
that extends Animal
. The Dog
class will inherit the eat()
method from Animal
without the need to define it again.
class Animal {
void eat(){
System.out.println("The animal eats");
}
}
class Dog extends Animal {
}
public class Main {
public static void main(String args[]) {
Dog dog1 = new Dog();
dog1.eat(); // valid, as Dog inherits from Animal
}
}
In the example above, dog1.eat();
will output: "The animal eats". This shows that the Dog
class inherited the eat()
method from the Animal
class via the extends
keyword.
It's essential to note that Java does not support multiple inheritance using classes - a class cannot extend
more than one class. However, a class can implement multiple interfaces using the implements
keyword.
Applying inheritance with the extends
keyword helps reduce redundancy in the program and improves code reusability, thus sticking to the Don't Repeat Yourself (DRY) programming principle. This leads to cleaner, easier-to-read code and reduces the chances for errors.
Overall, the extends
keyword serves a key role in the concept of inheritance in Java, making it possible to create more organized and efficient code structures.