implementing an interface

33
IMPLEMENTING AN INTERFACE

Upload: ninah-reyes

Post on 19-Jul-2016

13 views

Category:

Documents


1 download

DESCRIPTION

How to Implement an Interface in JavaAn introduction to basic implementation of interface including proper syntax

TRANSCRIPT

Page 1: Implementing an Interface

IMPLEMENTING AN

INTERFACE

Page 2: 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.

Page 3: Implementing an Interface

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.

Page 4: Implementing an Interface

Java, however, does provide an

alternative to multiple inheritance—an

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.

Page 5: Implementing an Interface

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 parent’s class, implements requires the subclass to implement its own

version of each method

Page 6: Implementing an Interface

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

Page 7: Implementing an Interface

//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.*/

Page 8: Implementing an Interface

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!"); } }

Page 9: Implementing an Interface

/*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 output—a 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.*/

Page 10: Implementing an Interface

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()+"says"); aSheepHerder.speak();

aSheepHerder.work(); System.out.println();

Page 11: Implementing an Interface

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*/

Page 12: Implementing an Interface

OUTPUT:

Page 13: Implementing an Interface

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); }

Page 14: Implementing an Interface

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; }

Page 15: Implementing an Interface

// 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())

Page 16: Implementing an Interface

return 1; else return 0; } }

//Because RectanglePlus implements Relatable, the

//size of any two RectanglePlus objects can be

//compared.

Page 17: Implementing an Interface

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.

Page 18: Implementing an 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.*/

Page 19: Implementing an Interface

Evolving Interfaces

Consider an interface that you have

developed called DoIt:

public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); }

Page 20: Implementing an Interface

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); }

Page 21: Implementing an Interface

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); }

Page 22: Implementing an Interface

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.

Page 23: Implementing an Interface

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

Page 24: Implementing an Interface

• 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

Page 25: Implementing an Interface

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;

Page 26: Implementing an Interface

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)); } }

Page 27: Implementing an Interface

OUTPUT:

Page 28: Implementing an Interface

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); }

Page 29: Implementing an Interface

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; }

Page 30: Implementing an Interface

//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

Page 31: Implementing an Interface

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

Page 32: Implementing an Interface

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