Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. There are two main keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between extends and implements is discussed.
Before getting into the differences, lets first understand in what scenarios each of the keywords are used.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.
Example:
class One {
public void methodOne()
{
// Some Functionality
}
}
class Two extends One {
public static void main(String args[])
{
Two t = new Two();
// Calls the method one
// of the above class
t.methodOne();
}
}
Extends | Implements |
By using “extends” keyword a class can inherit another class, or an interface can inherit other interfaces | By using “implements” keyword a class can implement an interface |
It is not compulsory that subclass that extends a superclass override all the methods in a superclass. | It is compulsory that class implementing an interface has to implement all the methods of that interface. |
Only one superclass can be extended by a class. | A class can implement any number of an interface at a time |
Any number of interfaces can be extended by interface. | An interface can never implement any other interface |
0 comments:
Post a Comment