In object-oriented programming, it is useful to define what a class should do, but not how.
An abstract method defines the signature of a method without providing implementation, and the subclass must implement that method.
An interface in Java allows you to completely separate the definition of what should be done from the implementation of how to do it.
An interface can specify methods without a body, which must be implemented by classes.
There is no limit to the number of classes that can implement an interface, and a class can implement multiple interfaces.
To implement an interface, the class must provide the implementation of the described methods.
Different classes can implement the same interface in different ways, but share the same set of methods.
The use of interfaces allows polymorphism, as objects from different classes can be treated interchangeably.
JDK 8 introduced the ability for interfaces to define default implementations for methods, allowing an interface to specify behavior.
Despite standard implementations, the original intent of interfaces to define only what remains largely unchanged.
The initial focus will be on traditional interfaces, with discussion of standard methods at the end of the chapter.
access interface name {
ret-type method-name1(param-list);
ret-type method-name2(param-list);
type var1 = value;
type var2 = value;
// ...
ret-type method-nameN(param-list);
type varN = value;
}
Access to an interface can be public or standard access (package-private).
If no access modifiers are included, the interface is accessible only to members of its package.
When declared as public, the interface can be used by any code, and must be in a file with the same name.
The interface name can be any valid identifier.
In the traditional form of an interface, methods are declared only with their return type and signature, essentially being abstract methods.
Classes that implement this interface must provide implementations for all their methods, which are implicitly public.
Variables in an interface are not instance variables; they are implicitly public, final and static, and must be initialized (they are constants).
Example of an interface definition:
public interface Series {
int getNext(); // returns the next number in the series
void reset(); // restart
void setStart(int x); // defines the initial value
}
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