Java implements keyword examples
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the implements keyword is used to make a class adheres to contract defined by an interface. The implemented class must provide concrete implementation for the methods defined by the interface. If not, the class must be abstract.
The following example illustrates a class implements an interface and provides detailed implementation for the interface's methods:
interface Vehicle { void start(); void stop(); } class Car implements Vehicle { void start() { // starts the engine } void stop() { // stop the engine } }
Unlike extends keyword, a class can implement multiple interfaces. The interface names are separated by commas. For example:
interface Peson { } interface Employee {} class Director implements Person, Employee { }
If the implemented class does not provide implementation for the interface's methods, the class must be abstract. For example:
interface Animal { void eat(); } abstract class Reptile implements Animal { abstract void crawl(); }
In that case, the first non-abstract class must implement the method. For example:
class Crocodile extends Reptile { void eat() { // eats } void crawl() { // crawls } }
Related keyword: class, interface, abstract and extends. See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
Public class extends Frame implements Mouse{
}
Does it mean that we have inherited a class Frame and an interface Mouse