Chapter 13 Interfaces

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

description

Chapter 13 Interfaces. Introduction. 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 - PowerPoint PPT Presentation

Transcript of Chapter 13 Interfaces

Page 1: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

University Of Hail 1

Chapter 13

Interfaces

Page 2: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Introduction

• 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.

Page 3: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

University Of Hail 3

Interfaceo 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

Page 4: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

University Of Hail 4

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

}

Page 5: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

University Of Hail 5

Interfaceo 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

Page 6: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Interface 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

Page 7: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Why 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

Page 8: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Why 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

Page 9: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Defining 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

Page 10: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Example

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.

Page 11: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Shape area, perimeter

• Rectangle (as defined by width w and height h):area = w hperimeter = 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

Page 12: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Shape 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.)

Page 13: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Implementing 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.)

Page 14: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Interface diagram

Page 15: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

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

Page 16: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

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

Page 17: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

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

Page 18: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Interfaces 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.

Page 19: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Syntax: 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.

Page 20: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Syntax: 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

Page 21: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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)

Page 22: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01• 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

Page 23: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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) { … }

}

Page 24: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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

Page 25: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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?

Page 26: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01Derived 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

Page 27: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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

Page 28: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

28

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

o Syntax: varName instanceof typeo varName is an object reference variableo 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

Page 29: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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

Page 30: Chapter 13 Interfaces

Prog

ram

min

g W

ith Ja

vaPr

ogra

mm

ing

With

Java

ICS2

01

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