Home >Java >javaTutorial >Implements vs. Extends: When to Use Which in Object-Oriented Programming?
Implements vs. Extends: A Comprehensive Guide
In object-oriented programming, understanding the distinction between "implements" and "extends" is crucial.
Implements
"Implements" is used when a class fulfills the contract specified by an interface. An interface declares a set of abstract methods (methods without implementation) that a class must implement. By implementing an interface, a class agrees to provide concrete implementations of all its methods.
For instance:
interface MyInterface { void doAction(); int doThis(int number); } class MyClass implements MyInterface { @Override public void doAction() { // Implement the method } @Override public int doThis(int number) { // Implement the method } }
Extends
"Extends" is used when a class inherits from another class. The child class (also known as a subclass) gains access to the parent class's (also known as a superclass) fields and methods. Subclasses can also override or extend the parent class's behavior.
For instance:
class SuperClass { private int num; public int getNum() { return num; } } class SubClass extends SuperClass { @Override public int getNum() { return num + 1; // Overriding the parent's implementation } }
Key Differences
When to Use
Understanding these concepts is essential for effective object-oriented design and code reusability.
The above is the detailed content of Implements vs. Extends: When to Use Which in Object-Oriented Programming?. For more information, please follow other related articles on the PHP Chinese website!