Implementing and Using Interfaces

Implementing and Using Interfaces

The implements Keyword
To use an interface, we include the implements keyword as part of our class definition

// java.applet.Applet is the superclass

public class Neko extends java.applet.Applet

implements Runnable
{ // but it also has Runnable behavior

}

After our class implements an interface, subclasses of our class will inherit those new methods (and can override or overload them) just as if our superclass had actually defined them.

If your class inherits from a superclass that implements a given interface, we don’t have to include the implements keyword in your own class definition.

Example-

interface Fruitlike
{
void decay();
void squish();
. . .
}

class Fruit implements Fruitlike
{
private Color myColor;
private int daysTilIRot;
. . .
}

interface Spherelike
{
void toss();
void rotate();
. . .
}

class Orange extends Fruit implements Spherelike
{
. . . // toss()ing may squish() me (unique to me)
}

Here the class Orange doesn’t have to say implements Fruitlike because, by extending Fruit, it already has!

Other Example-
class Sphere implements Spherelike
{ // extends Object
private float radius;
. . .
}

class Orange extends Sphere implements Fruitlike
{
. .// users of Orange never need know about the change!
}

Scroll to Top