Download presentation
Presentation is loading. Please wait.
Published byAudra Sharleen Wells Modified over 9 years ago
1
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces
2
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.
3
Programming With Java ICS201 University Of Hail3 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
4
Programming With Java ICS201 University Of Hail4 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); }
5
Programming With Java ICS201 University Of Hail5 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
6
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 Hail6
7
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 Hail7
8
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 Hail8
9
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
10
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.
11
Programming With Java ICS201 Shape area, perimeter Rectangle (as defined by width w and height h): area= w h perimeter= 2w + 2h Circle (as defined by radius r): area= r 2 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
12
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.)
13
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.)
14
Programming With Java ICS201 Interface diagram
15
Programming With Java ICS201 Complete 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; }
16
Programming With Java ICS201 Complete 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); }
17
Programming With Java ICS201 Complete 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; }
18
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.
19
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.
20
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
21
Programming With Java ICS201 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)
22
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 !!! Syntax: Defining an Interface
23
Programming With Java ICS201 University Of Hail23 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) { … } }
24
Programming With Java ICS201 University Of Hail24 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();
25
Programming With Java ICS201 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?
26
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
27
Programming With Java ICS201 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 200 4 7.98 true
28
Programming With Java ICS201 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
29
Programming With Java ICS201 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 29University Of Hail
30
Programming With Java ICS201 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 30 University Of Hail
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.