Interface

advertisement
Programming With Java
ICS201
Chapter 13
Interfaces
University Of Hail
1
Programming With Java
ICS201
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
• Java interface is a system that unrelated
objects use to interact with one another.
Programming With Java
ICS201
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
University Of Hail
3
Programming With Java
ICS201
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);
}
University Of Hail
4
Programming With Java
ICS201
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
University Of Hail
5
Programming With Java
ICS201
Interface 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
Programming With Java
ICS201
Why 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 three
abstract methods above
University Of Hail
7
Programming With Java
ICS201
Why 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
Programming With Java
ICS201
Defining 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
Programming With Java
ICS201
Example
Write a set of Circle, Rectangle, and Triangle
classes.
• Certain operations that are common to all
shapes.
perimeter
area
• Every shape has them but computes them
differently.
Programming With Java
ICS201
Shape area, perimeter
• Rectangle (as defined by width w and height h):
area
=wh
perimeter = 2w + 2h
• Circle (as defined by radius r):
area
=  r2
perimeter = 2  r
• Triangle (as defined by side lengths a, b, and c)
= √(s (s - a) (s - b) (s - c))
where s = ½ (a + b + c)
perimeter = a + b + c
area
Programming With Java
ICS201
Shape 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.)
Programming With Java
ICS201
Implementing 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.)
Programming With Java
ICS201
Interface diagram
Complete Circle class
Programming With Java
ICS201
// 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;
}
Complete Rectangle class
Programming With Java
ICS201
// 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);
}
Complete Triangle class
Programming With Java
ICS201
// 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;
}
Programming With Java
ICS201
Interfaces 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.
Programming With Java
ICS201
Syntax: 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.
Programming With Java
ICS201
Syntax: 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
Programming With Java
ICS201
Syntax: Defining an Interface (Cont’d)
We can define the speak() method as part of the Speakable
interface.
public interface Speakable {
public String speak(); // Abstract method
}
• Because speak() is no longer defined in Animal, the class
Animal should implement the Speakable interface.
public class Animal implements Speakable {
protected String kind; // Cow, dog, cat, etc.
public Animal() { }
public String speak() {
return ". . . ";
}
}
Syntax: Defining an Interface
Programming With Java
ICS201
• 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!!!
Programming With Java
ICS201
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 interface
public void listen() { … } // other methods implemented
public void call ( String number) { … } //method member
implemented
}
class Professor implements Communicate
{
public void talk() { … } //implementation of interface
public void listen() { … } // other methods implemented
void Lecture( String topic) { … }
}
University Of Hail
23
Programming With Java
ICS201
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();
University Of Hail
24
Programming With Java
ICS201
Exercise (Interface)
// What compile-time error generated for this program?
interface B
class InterfaceRefVariable
{
{
void display();
public static void main( String [] args)
}
{
class D0
B b = new D0();
{
b.display();
}
class D1 implements B
b = new D1();
{
b.display();
public void display()
b = new D2();
{
b.display();
System.out.println( "D1" );
}
}
}
}
class D2 implements B
{
public void display()
{
System.out.println( "D2" );
Incompatible types
}
}
Class D0 does not implement
the requested interface B
25
Programming With Java
ICS201
Derived 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
Example (Interface Reference)
Programming With Java
ICS201
// Interface extends one or more interfaces
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;
}
200
4
7.98
true
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
Programming With Java
ICS201
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.
University Of Hail
28
Programming With Java
ICS201
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
University Of Hail
29
Programming With Java
ICS201
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:
}
University Of Hail
Elephant: Drive
Horse: Drive
30
Download