Вы находитесь на странице: 1из 33

IMPLEMENTING AN

INTERFACE
In Java, a class can inherit from a
superclass that has inherited from another
superclass this represents single
inheritance with multiple generations. What
Java does not allow is for a class to inherit
directly from two or more parents.




Dealing with the possibility that
variables and methods in the parent classes
might have identical names, it might create a
conflict when the child class uses one of the
names. Also, when there are two or more
parents, which class should super() refer
when a child class has multiple parents? For
these reasons, multiple inheritance is
prohibited in Java.

The capability to inherit from more than
one class is called multiple inheritance.


Java, however, does provide an
alternative to multiple inheritancean
interface.

An interface looks much like a class,
except that all of its methods (if any) are
implicitly public and abstract, and all of its
data items (if any) are implicitly public, static,
and final.

An interface declares method headers,
but not the instructions within those methods.

When you create a class that uses an
interface, you include the keyword
implements and the interface name in the
class header. This notation requires the class to
include an implementation for every method
named in the interface.

Whereas using extends allows a
subclass to use nonprivate, nonoverridden
members of its parents class, implements
requires the subclass to implement its own
version of each method
EXAMPLE 1:

public abstract class Animal{
private String name;
public abstract void speak();
public String getName()
{
return name;
}
public void setName(String animalName){
name = animalName;
}
}
public class Dog extends Animal{
public void speak(){
System.out.println("Woof!");
}
}//Dog inherits Animal

//create interface


public interface Worker{
public void work();
}


/*this example gives the Worker interface a single
method named work(). When any class implements
Worker, it must either include a work() method or the
new class must be declared abstract, and then its
descendants must implement the method.*/
public class WorkingDog extends Dog implements
Worker{
private int hoursOfTraining;
public void setHoursOfTraining(int hrs{
hoursOfTraining = hrs;
}
public int getHoursOfTraining(){
return hoursOfTraining;
}
public void work(){
speak();
System.out.println("I am a dog who
works");
System.out.println("I have " +
hoursOfTraining + " hours of
professional training!");
}
}
/*Because the WorkingDog class implements the
Worker interface, it also must contain a work()
method that calls the Dog speak() method, and then
produces two more lines of outputa statement
about working and the number of training hours.*/

/*Note:
A class can extend another class without
implementing any interfaces. A class can also
implement an interface even though it does not
extend any other class. When a class both extends
and implements, like the WorkingDog class, by
convention the implements clause follows the
extends clause in the class header.*/
public class DemoWorkingDogs{
public static void main(String[] args){
WorkingDog aSheepHerder=new
WorkingDog();
WorkingDog aSeeingEyeDog = new
WorkingDog();
SheepHerder.setName("Simon, the Border
Collie");
SeeingEyeDog.setName("Sophie,the
German Shepherd");
SheepHerder.setHoursOfTraining(40);


System.out.println(SheepHerder.getName()+"sa
ys");
aSheepHerder.speak();
aSheepHerder.work();
System.out.println();

System.out.println(aSeeingEyeDog.getName()+"
says");
aSeeingEyeDog.speak();
aSeeingEyeDog.work();
}
}

/*The DemoWorkingDogs instantiates two WorkingDog objects.
Each object can use the following methods:
The setName() and getName() methods that WorkingDog
inherits from the Animal class
The speak() method that WorkingDog inherits from the Dog
class
The setHoursOfTraining()and getHoursOfTraining() methods
contained within the WorkingDog class
The work() method that the WorkingDog class was required
to contain when it used the phrase implements Worker; the work()
method also calls the speak() method contained in the Dog
class*/
OUTPUT:
Example 2

public interface Relatable {
// this (object calling isLargerThan)
// and other must be instances of
// the same class returns 1, 0, -1
// if this is greater than,
// equal to, or less than other public int
isLargerThan(Relatable other);
}
public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}

public RectanglePlus(Point p){
origin = p;
}
public RectanglePlus(int w, int h){
origin = new Point(0, 0);
width = w; height = h;
}
public RectanglePlus(Point p, int w, int h){
origin = p;
width = w;
height = h; }

//a method for moving the rectangle
public void move(int x, int y){
origin.x = x;
origin.y = y;
}
// a method for computing
// the area of the rectangle
public int getArea(){
return width * height;
}

// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other){
RectanglePlus otherRect =
(RectanglePlus)other;
if (this.getArea() <
otherRect.getArea())
return -1;
else if (this.getArea() >
otherRect.getArea())

return 1;
else
return 0;
}
}



//Because RectanglePlus implements Relatable, the
//size of any two RectanglePlus objects can be
//compared.
Using an Interface as a Type

When you define a new interface, you
are defining a new reference data type. You
can use interface names anywhere you can
use any other data type name. If you define a
reference variable whose type is an interface,
any object you assign to it must be an
instance of a class that implements the
interface.

/*a method for finding the largest object in a pair of
objects, for any objects that are instantiated from a
class that implements Relatable*/

public Object findLargest(Object object1, Object
object2){
Relatable obj1 = (Relatable)object1;
Relatable obj2 = (Relatable)object2;
if ((obj1).isLargerThan(obj2) > 0)
return object1;
else
return object2; }


/*By casting object1 to a Relatable type, it can invoke
the isLargerThan method.*/

Evolving Interfaces

Consider an interface that you have
developed called DoIt:

public interface DoIt {

void doSomething(int i, double x);
int doSomethingElse(String s);

}

Suppose that, at a later time, you want
to add a third method to DoIt, so that the
interface now becomes:

public interface DoIt{

void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x,
String s);

}

If you make this change, then all
classes that implement the old DoIt interface
will break because they no longer implement
the old interface.

Try to anticipate all uses for interface
and specify it completely from the beginning.
Create a DoItPlus interface that extends DoIt:

public interface DoItPlus extends DoIt {
boolean didItWork(int i, double x,
String s);
}

Abstract Classes vs. Interfaces

Abstract classes and interfaces are similar
in that you cannot instantiate concrete
objects from either one.
Abstract classes differ from interfaces
because abstract classes can contain
nonabstract methods, but all methods
within an interface must be abstract.
A class can inherit from only one abstract
superclass, but it can implement any
number of interfaces.
Creating Interfaces to Store Related Constants

Interfaces can contain data fields, but they
must be public, static, and final.

Public:
interface methods cannot contain
method bodies; without public method
bodies, you have no way to retrieve private
data
Static:
you cannot create interface objects

Final:
without methods containing bodies, you
have no way, other than at declaration, to
set the data fields values, and you have no
way to change them

Example:

public interface PizzaConstants{
public static final int SMALL_DIAMETER = 12;
public static final int LARGE_DIAMETER = 16;
public static final double TAX_RATE = 0.07;
public static final String COMPANY =
"Antonio's Pizzeria";
}

public class PizzaDemo implements
PizzaConstants{
public static void main(String[]
args){
double specialPrice = 11.25;

System.out.println("Welcome to
"+COMPANY);

System.out.println("We are having a
special offer:\na "+ SMALL_DIAMETER +" inch
pizza with four toppings\nor a " +
LARGE_DIAMETER + " inch pizza with one
topping\nfor only $" + specialPrice);

System.out.println("With tax, that
is only $" + (specialPrice + specialPrice *
TAX_RATE));

}
}

OUTPUT:
More examples:

public interface Relatable {

/* this (object calling isLargerThan) and other
must be instances of the same class returns 1, 0, -1
if this is greater than, equal to, or less than other */

public int isLargerThan(Relatable other);

}// public interface Relatable

public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;

//four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}

public RectanglePlus(Point p) {
origin = p;
}

public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

//a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}


//a method for computing the area of the rectangle

public int getArea() {
return width * height;
}

//a method to implement Relatable interface

public int isLargerThan(Relatable other) {
RectanglePlus otherRect=(RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea()>otherRect.getArea())
return 1;
else
return 0;

}// public int isLargerThan(Relatable other)

}// public class RectanglePlus implements Relatable


interface Animal {
public void eat();
public void travel();
}

public class MammalInt implements Animal{

public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
} // public class MammalInt implements Animal
public interface MyInterface {
public String hello = "Hello";
public void sayHello();
}

public interface MyInterface {
public String goodbye = "Goodbye";
public void sayHello();
}

public class MyInterfaceImpl implements MyInterface,
MyOtherInterface {

public void sayHello() {
System.out.println(MyInterface.hello);
}
public void sayGoodbye() {
System.out.println(MyInterface.goodbye);
}

}// public class MyInterfaceImpl implements MyInterface,
//MyOtherInterface
References:
http://docs.oracle.com/javase/tutorial/java/IandI/
usinginterface.html

http://www.tutorialspoint.com/java/java_interface
s.htm

http://tutorials.jenkov.com/java/interfaces.html#i
mplementating-an-interface

Java Programming 6
th
Edition by Joyce Farrell

Java: An Introduction to Problem Solving and
Programming 6
th
Edition by Walter Savitch

Вам также может понравиться