|
||
|
Lesson 6
Objective
|
Inside interfaces Create interfaces to define general characteristics |
|
|
Interfaces are Java constructs similar to classes that don't contain any functioning code. Interfaces are used to define
the general design for a class without getting into the details of an implementation.
The idea behind interfaces is that you can use them to define the general make-up of a type of class and then apply it to create the classes themselves. Following is an example of a simple interface:
interface Fish {
public void swim();
public void eat();
}
Notice that the methods defined in the Fish interface are simply declarations and contain no actual code.
To create a class based on an interface, you must use the implements keyword, like this: class Shark implements Fish { boolean isHungry; public void swim() { isHungry = true; } public void eat() { isHungry = false; } } You could also create other types of fish based on the Fish interface, in which case they would provide suitable implementations of the swim() and eat() methods. The benefit of implementing an interface in this situation is that all fish classes would have commonly supported methods, as defined by the Fish interface.
Although interfaces primarily consist of method declarations, it is possible to declare member variables in them as well.
However, any member variable declared in an interface is implicitly made static and final.
Java Interfaces - Exercise
Click the Exercise button to create an interface.
Java Interfaces - Exercise |
||
|
|
||