60 likes | 213 Views
CSE 1341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 21. Note Set 21 Overview. Java Interfaces. Interface. Group of related methods with empty bodies A class implements an interface Where have we seen implement before?
E N D
CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 21
Note Set 21 Overview • Java Interfaces
Interface • Group of related methods with empty bodies • A class implements an interface • Where have we seen implement before? • Declares what a class should be able to do but not how to do it • Why? • Common that different groups of programmers will need to implement classes that can interact • Interface defined a contract… • if your class implements and interface, it must provide an implementation for every method in the interface
Sample Interface All methods in an interface are implicitly declared public… public interface Drivable { int turn (int degrees); intchangeLanes (int lane); int accelerate (double speed); //other method headers } Any class that implements an interface must provide an implementation of all methods in that interface… public class MyCarimplements Drivable { public int turn(int degrees) { //code to turn this object the correct //number of degrees } //Implementation for all other methods in the //interface }
Interfaces as Type Drivable car = new MyCar(); Can be used to call any method that exists in the Drivable interface. If MyCar implements any other methods not in Drivable, they will not be accessible through variable car Drivable d = new Drivable(); //Error!!! Can use an interface as a type of a reference variable. Objects that are referenced by an interface-typed variable must implement the interface
Robot Example Navigator robot = null; String s; //Read 1st line from data.txt into s if(s.equals(“tach”)) robot = new TachoNavigator(…); else robot = new CompassNavigator(…); data.txt tach