Follow
Publications: 74 | Followers: 0

Interfaces - cs.colostate.edu

Publish on Category: Birds 0

Interfaces
CS163 Fall 2018
Relatedness of types
Consider the task of writing classes to represent 2D shapes such asCircle,Rectangle, andTriangle.There are certain attributes or operations that are common to all shapes:perimeter, areaBy being a Shape, you promise that you can compute those attributes, but each shape computes them differently.
Interface as a contract
Analogous to the idea of roles or certifications in real life:"I'm certified as a CPA accountant. The certification assures you that I know how to do taxes, perform audits.”Compare to:"I'm certified as a Shape. That means you can be sure that I know how to compute my area and perimeter.”
The areaand perimeterof shapes
Rectangle (as defined by widthwand heighth):area =whperimeter = 2w+ 2hCircle (as defined by radiusr):area =r2perimeter = 2rTriangle (as defined by side lengthsa,b, andc)area = √(s(s-a) (s-b) (s-c))wheres= ½ (a+b+c)perimeter =a+b+c
Interfaces
interface: A list of methods that a class promises to implement.Inheritance encodes an is-a relationship and provides code-sharing.An Executive object can be treated as aStaffMember, andExecutive inheritsStaffMember’scode.An interface specifies what an object is capable of; no code sharing.Only methodstubsin the interfaceObjectcan-act-asany interface itimplementsA Rectangle does what you expect from a Shape as long as it implements the interface.
Java Interfaces
An interface for shapes:public interface Shape {public double area();public double perimeter();}This interface describes the functionality common to all shapes.(Every shape knows how to compute its area and perimeter.)Interface declaration syntax:public interface<name>{public<type><name>(<type><name>, ...,<type><name>);public<type><name>(<type><name>, ...,<type><name>);...public<type><name>(<type><name>, ...,<type><name>);}All methods are public!
Implementing an interface
public class CircleimplementsShape {private double radius;// Constructs a new circle with the given radius.publicCircle(doubleradius) {this.radius= radius;}// Returns the area of the circle.public double area() {returnMath.PI* radius * radius;}// Returns the perimeter of the circle.public double perimeter() {return 2.0 *Math.PI* radius;}}
Implementing an interface
A class can declare that itimplementsan interface.This means the class needs to contain an implementation for each of the methods in that interface.(Otherwise, the class will fail to compile.)Syntax for implementing an interfacepublic class<name>implements<interface name>{...}
Requirements
If we write a class that claims act like aShapebut doesn't implement theareaandperimetermethods, it will not compile.Example:public class Bananaimplements Shape{//without implementing area orperimiter}The compiler error message:Banana.java:1: Banana is not abstract and does not override abstract method area() in Shapepublic class Banana implements Shape {^
Diagramming an interface
We draw arrows from the classes to the interface(s) they implement.Like inheritance, an interface represents an is-a relationship (a Circle is a Shape).
Rectangle
public class Rectangleimplements Shape{private double width;private double height;// Constructs a new rectangle with the given dimensions.publicRectangle(doublewidth, 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);}}
Triangle
public class Triangleimplements Shape{private double a;private doubleb;private doublec;// Constructs a new Triangle given side lengths.publicTriangle(doublea, doubleb, doublec) {this.a= a;this.b=b;this.c=c;}// Returns a triangle's area using Heron's formula.public double area() {doubles= (a +b+c) / 2.0;returnMath.sqrt(s* (s– a)*(s–b)*(s-c));}// Returns the perimeter of the triangle.public double perimeter() {return a +b+c;}}
Interfaces and polymorphism
Polymorphism is possible with interfaces.Example:public static voidprintInfo(Shapes) {System.out.println("Theshape: " +s);System.out.println("area: " +s.area());System.out.println("perim: " +s.perimeter());System.out.println();}Any object that implements the interface may be passed as the parameter to the above method.Circle circ = new Circle(12.0);Triangle tri = new Triangle(5, 12, 13);printInfo(circ);printInfo(tri);
Interface is a type!
Interfaces and polymorphism
We can create an array of an interface type, and store any object implementing that interface as an element.Circle circ = new Circle(12.0);Rectanglerect= new Rectangle(4, 7);Triangle tri = new Triangle(5, 12, 13);Shape[] shapes = {circ, tri,rect};for (inti= 0;i<shapes.length;i++) {printInfo(shapes[i]);}Each element of the array executes the appropriate behavior for its object when it is passed to theprintInfomethod, or whenareaorperimeteris called on it.
Comments about Interfaces
The term interface also refers to the set of public methods through which we can interact with objects of a class.Methods of an interface are abstract.Think of an interface as an abstract base class with all methods abstractInterfaces are used to define a contract for how you interact with an object, independent of the underlying implementation.Separate behavior (interface) from the implementation
Commonly used Java interfaces
The Java class library contains several interfaces:Comparable– allows us to order the elements of an arbitrary classSerializable(injava.io) – for saving objects to a file.List, Set, Map,Iterator(injava.util) – describe data structures for storing collections of objects
The Java Comparable interface
A class can implement theComparableinterface to define an ordering for its objects.public interface Comparable<E> {publicintcompareTo(Eother);}public class Employeeimplements Comparable<Employee>{ … }A call ofa.compareTo(b)should return:a value < 0 ifacomes "before"bin the ordering,a value > 0 ifacomes "after"bin the ordering,or 0 ifaandbare considered "equal" in the ordering.
Comparableand sorting
If you implement Comparable, you can sort arbitrary objects using the methodArrays.sortStaffMember[] staff = new StaffMember[3];staff[0] = new Executive(…);staff[1] = new Employee(…)staff[2] = new Hourly(…);staff[3] = new Volunteer(…);Arrays.sort(staff);Note that you will need to provide an implementation ofcompareTo
compareTotricks
Delegation trick - If your object's attributes are comparable (such as strings), you can use theircompareTo:// sort by employee namepublicintcompareTo(StaffMemberother) {returnname.compareTo(other.getName());}

0

Embed

Share

Upload

Make amazing presentation for free
Interfaces - cs.colostate.edu