Java Reference
In-Depth Information
An interface specifies a protocol that an object guarantees to offer when it interacts with other objects. It specifies
the protocol in terms of abstract and default methods. A specification is implemented at some time by someone, and
so is the case with an interface. An interface is implemented by a class. When a class implements an interface, the
class provides implementations for all abstract methods of the interface. A class may provide a partial implementation
of the abstract methods of the interface, and in that case, the class must declare itself
abstract
.
A class that implements an interface uses an “implements” clause to specify the name of the interface. An
“implements” clause consists of the keyword
implements
, followed by a comma-separated list of interface types. A
class can implement multiple interfaces. Let's focus on a class implementing only one interface for now. The general
syntax for a class declaration that implements an interface looks as follows:
<modifiers> class <class-Name> implements <comma-separated-list-of-interfaces> {
// Class body goes here
}
Suppose there is a
Fish
class.
public class Fish {
// Code for Fish class goes here
}
Now, you want to implement the
Swimmable
interface in the
Fish
class. The following code shows the
Fish
class
that declares that it implements the
Swimmable
interface:
public class Fish
implements Swimmable
{
// Code for the Fish class goes here
}
The text in boldface font shows the changed code. The above code for the
Fish
class will not compile.
A class inherits all abstract and default methods from the interfaces it implements. Therefore, the
Fish
class
inherits the abstract
swim()
method from the
Swimmable
interface. A class must be declared abstract if it contains
(inherited or declared) abstract methods. You have not declared the
Fish
class abstract. This is the reason
the above declaration will not compile. In the following code, the
Fish
class overrides the
swim()
method to
provide an implementation:
public class Fish implements Swimmable {
// Override and implement the swim() method
public void swim() {
// Code for swim method goes here
}
// More code for the Fish class goes here
}
The class that implements an interface must override to implement all abstract methods declared in the
interface. Otherwise, the class must be declared abstract. Note that default methods of an interface are also inherited
by the implementing classes. The implanting classes may choose (but is not required) to override the default
methods. The static methods in an interface are not inherited by the implementing classes.
A class implementing interfaces can have other methods that are not inherited from the implemented interfaces.
Other methods can have the same name and different number and/or types of parameters than the one declared in
the implemented interfaces.