1 / 6

CSE 1341 - Honors Principles of Computer Science I

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?

karik
Download Presentation

CSE 1341 - Honors Principles of Computer Science I

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. CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 21

  2. Note Set 21 Overview • Java Interfaces

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

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

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

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

More Related