Implements vs extends: When to use? What's the difference?
In Java, the extends
keyword is used to inherit from a superclass, and the implements
keyword is used to implement an interface.
Here are the key differences between the two:
- A class can only inherit from a single superclass using the
extends
keyword, but it can implement multiple interfaces. - A class that extends a superclass inherits all of its methods and fields, while a class that implements an interface must implement all of the methods defined in the interface.
Here's an example of how you might use the extends
and implements
keywords in a Java class:
public class MyClass extends SuperClass implements Interface1, Interface2 {
// class definition goes here
}
In this example, MyClass
is extending the SuperClass
and implementing both Interface1
and Interface2
.
To decide whether to use extends
or implements
, consider the following:
- If you want to create a new class that is a modified version of an existing class, with additional methods and fields, you should use
extends
. - If you want to create a new class that is compatible with a specific interface and has a specific set of methods, but you don't need to add any additional fields or methods, you should use
implements
.
Keep in mind that a class can only inherit from a single superclass, but it can implement multiple interfaces. So, if you need to inherit from multiple classes or create a class that is compatible with multiple interfaces, you can use both extends
and implements
in your class definition.