1 / 30

Chapter 13 Interfaces

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

seanna
Download Presentation

Chapter 13 Interfaces

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13 Interfaces University Of Hail

  2. 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. Interface • An interface is something like an abstract class • However, an interface is not a class • 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

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

  5. Interface • Interface variable is implicitly public, static and final • Interface method is implicitly publicand abstract (is not implemented by this class) • A class can implement one or more interfaces • An interface can be implemented by several classes University Of Hail

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

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

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

  9. Defining Interfaces Use the interfacekeyword public interface Vehicle { public void Method1(); public void Method2(); } Like abstract methods, the signature is terminated with a semi-colon

  10. 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. 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 = 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

  12. 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. 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. Interface diagram

  15. 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. 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. 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. 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. 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. Syntax: Implementing an Interface public class ClassNameimplements 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. Syntax: Defining an Interface (Cont’d) We can define the speak() method as part of the Speakable interface. publicinterfaceSpeakable { public String speak(); // Abstract method } • Because speak() is no longer defined in Animal, the class Animal should implement the Speakable interface. public class Animal implementsSpeakable { protected String kind; // Cow, dog, cat, etc. public Animal() { } public String speak() { return ". . . "; } }

  22. Syntax: Defining an Interface public class Cat extends Animal implementsSpeakable { public Cat() { kind = "cat"; } public String speak() { return "meow"; } } • Subclasses of Animal can now implement the Speakable interface in their own distinct ways. public class Cow extends Animal implementsSpeakable { public Cow() { kind = "cow"; } public String speak() { return "moo"; } } Inheritance: A Cat is both an Animal and a Speakable!!!

  23. Example (Interface) interface Communicate { int LOUD = 0; int SOFT = 1; int OFF = 2; void talk(); voidlisten(); } class Telephone implements Communicate { publicvoid talk() { … } //implementation of interface publicvoid listen() { … } // other methods implemented publicvoid call ( String number) { … } //method member implemented } class Professor implements Communicate { publicvoid talk() { … } //implementation of interface publicvoid listen() { … } // other methods implemented void Lecture( String topic) { … } } University Of Hail

  24. Example (Interface) • The keyword implements indicates that the class implements one or more interfaces. • Using Objects with common interfaces methods Professor prof = new Professor(" XXXXXX" ); Telephone tel = new Telephone(" 111" ); prof.listen(); tel.listen(); University Of Hail

  25. Exercise (Interface) // What compile-time error generated for this program? classInterfaceRefVariable { publicstaticvoid main( String[]args) { B b=new D0(); b.display(); b = new D1(); b.display(); b =new D2(); b.display(); } } interface B { void display(); } class D0 { } class D1 implements B { publicvoid display() { System.out.println( "D1" ); } } class D2implementsB { publicvoid display() { System.out.println( "D2" ); } } Incompatible types Class D0 does not implement the requested interface B

  26. 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. Example (Interface Reference) interfaceJ { inti=200; int J1(); } interface K { double K1(); } interface L extendsJ, K { boolean L1(); } class I implements L { publicint J1() { return 4; } // Interface extends one or more interfaces public double K1() { return 7.98; } public boolean L1() { returntrue; } } classInterfaceInheritance { publicstaticvoid 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()); } } 200 4 7.98 true 27

  28. The instanceof Operator The instanceof operator is used to determine if an object is of a particular class or implements a specific interface. • Syntax: varName instanceof type • varName is an object reference variable • type is the name of either a class or an interface • The expression evaluates to true if varName is a type. Otherwise, it evaluates to false. University Of Hail 28

  29. Example (The instanceof Operator) abstract class Fish { abstractvoid 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 { publicstaticvoid 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

  30. Example (The instanceof Operator) interface Vehicle { void drive(); } abstractclass Mammal { } class Bear extends Mammal { } class Elephant extends Mammal implements Vehicle { publicvoid drive() { System.out.println( "Elephant: Drive" ); } } class Horse extends Mammal implements Vehicle { publicvoid drive() { System.out.println( "Horse:Drive" ); } } class Lion extends Mammal{ } class InstantofInterface { publicstaticvoid 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( intj = 0; j < 4; j++) { if ( m[j] instanceof Vehicle) { Vehicle v = (Vehicle)m[j]; v.drive(); } } } } Output: Elephant: Drive Horse: Drive University Of Hail 30

More Related