After defining an interface, one or more classes can implement it.
To implement an interface, use the implements clause in the class definition.
The class must implement all the methods required by the interface.
The general form of a class that includes the implements clause is:
class classname extends superclass implements interface {
// class-body
}
To implement more than one interface, the interfaces are separated by commas.
The extends clause is optional when implementing interfaces.
Methods that implement an interface must be declared as public.
The signature of the implementing method must exactly match the signature specified in the interface.
Example implementing the Series interface:
In this example, the ByTwos class implements the Series interface, generating a series of numbers that increases by two with each call to the getNext() method.
The getNext(), reset(), and setStart() methods in the ByTwos class are declared with the public access specifier.
This is necessary because when implementing a method defined by an interface, it must be declared as public.
All members of an interface are implicitly public, so the implementation in the class must respect this access modifier.
Here is a class that demonstrates ByTwos:
The inclusion of the getPrevious() method did not require any changes to the Series interface.
The flexibility of modifying implementations without affecting the interface is one of the main advantages of using interfaces in object-oriented programming.
Abstract classes:
If a class includes an interface but does not implement all the methods defined by it, it must be declared abstract.
Abstract classes cannot be instantiated directly (that is, objects cannot be created from them).
They can be used as abstract superclasses, allowing subclasses to provide the full implementation of the interface's methods.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3