programming with java ics201 university of hail1 chapter 13 interfaces

30
Programming With Java Programming With Java ICS201 University Of Hail 1 Chapter 13 Interfaces

Upload: audra-sharleen-wells

Post on 03-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 1

Chapter 13

Interfaces

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Introduction

• In English, an interface is a device or system that unrelated entities use to interact. – A remote control is an interface between you

and a television set– English language is an interface between two

people

• Java interface is a system that unrelated objects use to interact with one another.

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 3

Interface

o An interface is something like an abstract class

However, an interface is not a class

o The syntax for defining an interface is similar to that of

defining a class

Except the word interface is used in place of class

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 4

Interface

o An interface specifies a set of methods that any class that

implements the interface must have

It contains method headings and constant definitions

It contains neither instance variables nor any complete

method definitions

Example: interface A

{

int x = 10;

public void display( String s);

}

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 5

Interface

o Interface variable is implicitly public, static and final

o Interface method is implicitly public and abstract (is not

implemented by this class)

o A class can implement one or more interfaces

o An interface can be implemented by several classes

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Interface Vs. Class

An interface is similar to a class in :

• An interface can contain any number of methods.

• An interface is written in a file with a .java extension.

However, an interface is different from a class in:

• You cannot instantiate an interface.

• An interface does not contain any constructors.

• All of the methods in an interface are abstract.

• An interface is not extended by a class; it is

implemented by a class.

• An interface can extend multiple interfaces.

University Of Hail 6

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Why do we use Interfaces?

To have unrelated classes implement similar methods● Example:– Class Line and class MyInteger

They are not related through inheritance● You want both to implement comparison methods

– checkIsGreater(Object x, Object y)– checkIsLess(Object x, Object y)– checkIsEqual(Object x, Object y)

– Define Comparison interface which has the threeabstract methods above

University Of Hail 7

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Why do we use Interfaces?

To model multiple inheritance

– A class can implement multiple interfaces while it can extend only one class

University Of Hail 8

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Defining Interfaces

Use the interface keyword

public interface Vehicle {public void Method1();public void Method2();

} Like abstract methods, the signature is terminated

with a semi-colon

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Example

Write a set of Circle, Rectangle, and Triangle classes.

• Certain operations that are common to all shapes.

perimeterarea

• Every shape has them but computes them differently.

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Shape area, perimeter

• Rectangle (as defined by width w and height h):area = w h

perimeter = 2w + 2h

• Circle (as defined by radius r):area = r2

perimeter = 2 r

• Triangle (as defined by side lengths a, b, and c)area = √(s (s - a) (s - b) (s - c))

where s = ½ (a + b + c)

perimeter = a + b + c

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Shape interface

public interface Shape { public double area(); public double perimeter();}

– This interface describes the features common to all shapes.(Every shape has an area and perimeter.)

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Implementing an interface

public class name implements interface { ...}

• This means the class must contain each of the abstract methods in that interface. (Otherwise, it will not compile.)

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Interface diagram

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Complete Circle class

// Represents circles.public class Circle implements Shape { private double radius; //Constructs a new circle with the given radius. public Circle(double radius) { this.radius = radius; } // Returns the area of this circle. public double area() { return Math.PI * radius * radius; } // Returns the perimeter of this circle. public double perimeter() { return 2.0 * Math.PI * radius; }}

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Complete Rectangle class

// Represents rectangles.public class Rectangle implements Shape { private double width; private double height; // Constructs a new rectangle with the given dimensions. public Rectangle(double width, double height) { this.width = width; this.height = height; }

// Returns the area of this rectangle. public double area() { return width * height; } // Returns the perimeter of this rectangle. public double perimeter() { return 2.0 * (width + height); }}

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Complete Triangle class

// Represents triangles.public class Triangle implements Shape { private double a; private double b; private double c; // Constructs a new Triangle given side lengths. public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double area() { double s = (a + b + c) / 2.0; return Math.sqrt(s*(s–a)*(s-b)*(s-c)); } // Returns the perimeter of this triangle. public double perimeter() { return a + b + c; }}

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Interfaces Versus Classes

• An interface type is similar to a class,

but there are several important

differences:

– All methods in an interface type are

abstract; they don't have an

implementation

– All methods in an interface type are

automatically public

– An interface type cannot have instance

variables, although they can have

constants.

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Syntax: Defining an Interface

public interface InterfaceName { // constants

// method signatures }

Example: public interface Measurable {

double getMeasure(); }

• To define an interface and its method signatures. – The methods are automatically public. – Variables are automatically public , static, or final.

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Syntax: Implementing an Interface

 public class ClassName implements InterfaceName, InterfaceName, ... { // methods // instance variables }

Example: public class BankAccount implements Measurable { // Other BankAccount methods public double getMeasure() { // Method implementation } }

Purpose:To define a new class that implements the methods of an interface

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

We can define the speak() method as part of the Speakable interface.

public interface Speakable { public String speak(); // Abstract method}

public class Animal implements Speakable { protected String kind; // Cow, dog, cat, etc. public Animal() { } public String speak() { return ". . . "; }}

• Because speak() is no longer defined in Animal, the class Animal should implement the Speakable interface.

Syntax: Defining an Interface (Cont’d)

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

• Subclasses of Animal can now implement the Speakable interface in their own distinct ways. public class Cat extends Animal implements Speakable { public Cat() { kind = "cat"; } public String speak() { return "meow"; }}

public class Cow extends Animal implements Speakable { public Cow() { kind = "cow"; } public String speak() { return "moo"; }}

Inheritance: A Cat is both an Animal and a Speakable!!!

Syntax: Defining an Interface

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 23

Example (Interface)interface Communicate{

int LOUD = 0;int SOFT = 1;int OFF = 2;void talk();void listen();

}class Telephone implements Communicate {

public void talk() { … } //implementation of interfacepublic void listen() { … } // other methods implementedpublic void call ( String number) { … } //method member implemented

}class Professor implements Communicate{

public void talk() { … } //implementation of interfacepublic void listen() { … } // other methods implementedvoid Lecture( String topic) { … }

}

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

University Of Hail 24

Example (Interface)

o The keyword implements indicates that the class

implements one or more interfaces.

o Using Objects with common interfaces methods

Professor prof = new Professor(" XXXXXX" );

Telephone tel = new Telephone(" 111" );

prof.listen();

tel.listen();

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

25

Exercise (Interface)

interface B{

void display();}class D0 {}class D1 implements B{

public void display(){

System.out.println( "D1" );}

}class D2 implements B{

public void display() {

System.out.println( "D2" );}

}

class InterfaceRefVariable{ public static void main( String [] args) {

B b = new D0(); b.display();b = new D1(); b.display();b = new D2(); b.display();

}}

Incompatible types Class D0 does not implement

the requested interface B

// What compile-time error generated for this program?

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1Derived Interfaces

• Like classes, an interface may be derived from a base interface– This is called extending the interface– The derived interface must include the phrase

extends BaseInterfaceName

• If more than one interface is implemented, each is listed, separated by commas.

– The concrete class must implement all the method headings listed in the definition(s) of any methods in the derived interface as well as any methods in the base interface

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

27

Example (Interface Reference)

interface J { int i=200;

int J1();}interface K {

double K1();}interface L extends J, K{

boolean L1();}class I implements L {

public int J1(){

return 4;}

public double K1(){

return 7.98; } public boolean L1() {

return true; }}class InterfaceInheritance{ public static void main( String[] args) {

I a = new I();System.out.println(a.i);System.out.println(a.J1());System.out.println(a.K1());System.out.println(a.L1());

} }

27

// Interface extends one or more interfaces

2004

7.98true

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

28

The instanceof Operator

o The instanceof operator is used to determine if an object is of a particular class or implements a specific interface.

o Syntax: varName instanceof type

o varName is an object reference variable

o type is the name of either a class or an interface

o The expression evaluates to true if varName is a type. Otherwise, it evaluates to false.

28University Of Hail

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

29

Example (The instanceof Operator)abstract class Fish{

abstract void display(); }abstract class SaltWtrFish extends Fish{}abstract class FreshWtrFish extends Fish{}class Trout extends FreshWtrFish{

void display(){

System.out.println( "Trout" ); }

}class Tuna extends SaltWtrFish{

void display(){

System.out.println( "Tuna" );}

}

class InstantofOperator

{

public static void main( String[] arg)

{

Fish f[] = new Fish[3];

f[0] = new Trout();

f[1] = new Tuna();

f[2] = new Trout();

for(int j = 0; j < 3; j++)

if ( f[j] instanceof FreshWtrFish )

f[j].display();

}

}

Output:

Trout

Trout

29University Of Hail

Pro

gra

mm

ing

Wit

h Java

Pro

gra

mm

ing

Wit

h Java

ICS

20

1

30

Example (The instanceof Operator)interface Vehicle{

void drive();}abstract class Mammal { }class Bear extends Mammal { }class Elephant extends Mammal implements Vehicle{

public void drive(){

System.out.println( "Elephant: Drive" );}

}class Horse extends Mammal implements Vehicle{

public void drive(){

System.out.println( "Horse:Drive" );}

}class Lion extends Mammal{ }

class InstantofInterface{

public static void main( String[] ar){

Mammal m[] = new Mammal[4];m[0]=new Elephant();m[1]=new Bear(); m[2]=new Horse();m[3]=new Lion();for( int j = 0; j < 4; j++){ if ( m[j] instanceof Vehicle) { Vehicle v =

(Vehicle)m[j]; v.drive(); }

}}

}Output:

Elephant: Drive

Horse: Drive

30University Of Hail