NYU COMS W1007 - Interfaces and Abstraction

Unformatted text preview:

Interfaces and AbstractionCOMS W1007Introduction to Computer ScienceChristopher Conway17 June 2003Review: Inheritance•When objects have broadly similar characteristics, butspecialized behavior, we can relate them throughinheritance.•A subclass inherits the public and protected membersof its superclass.•The derived class generally has an is-a relationshipwith the parent.•A class is assignment-compatible with any classabove it in the class hierarchy.•Inheritance enables polymorphism—heterogeneousobjects can be treated uniformly.Abstract ClassesSometimes a superclass can’t fully define all the behaviorof an object—certain behavior only makes sense for aparticular subclass.If a class is too general to be useful on its own, we candeclare it abstract. You cannot create an instance of anabstract class. It only serves as a base for concretesubclasses.Methods that need to be defined by a subclass are alsomarked abstract and have no body. Any class with anabstract method must also be declared abstract.Abstract Classes: InputStreamThe class InputStream in java.io defines operationson a stream of input data.•read returns the next byte of the input•skip(n) skips the next n bytes of input.skip can be defined using read, but read depends onwhat kind of data is being read. read is declaredabstract; InputStream is an abstract class.package java.io ;public abstract class InputStream {/* Reads the next byte of data from the input stream.Returns -1 if no more data is available. */public abstract int read() ;/* Skips the next n bytes of input. Returns the actual* number of bytes skipped. */public long skip(long n) {long i = n ;while( i > 0 && read() > 0 ) {i-- ;}return n-i ;}...}Abstract Classes: InputStream, 2The concrete subclasses of InputStream define readfor the particular kind of data they operate on.InputStreamAudioInputStreamFileInputStreamByteArrayInputStreamInterfacesSometimes we want to define a type by describing itsfields and methods without defining any specific behavior.An interface is an extreme form of the abstract class: all ofits methods are abstract. An interface defines a externalcontract that a class agrees to implement.A class may only extend one superclass, but it mayimplement any number of interfaces.Interfaces: ComparableThe interface Comparable in java.lang provides amethod for comparing two objects in a standard way.compareTo takes a single Object parameter andreturns:•-1 if the implementing object is less than theparameter.•0 if the implementing object is equal to the parameter.•1 if the implementing object is greater than theparameter./* This interface imposes a total ordering on* the objects * of each class that implements* it. */package java.lang ;public interface Comparable {/* Compares this object with the specified* object for order. Returns a negative integer,* zero, or a positive integer as this object* is less than, equal to, or greater than the* specified object. */int compareTo(Object o) ;}Sorting with ComparableAn interface defines a type, just like a class. Any class thatimplements an interface can be used polymorphicallywherever that interface is required.We can use interfaces to define generic methods thatoperate on a wide variety of classes polymorphically. Ourprevious sorting algorithm only worked on type int. Nowwe can define it to operate on any Comparable object.public static void sort(Comparable[] objs) {/* iterate over the list and insert the itemsinto the sorted list */for( int i=1 ; i < objs.length ; i++ ) {int n = objs[i] ;/* "push back" items that should comeafter n */int j = i ;while( --j >= 0 && n.compareTo(objs[j]) < 0 ) {objs[j+1] = objs[j] ;}objs[j+1] = n ;}}public class Point implements Comparable {double x, y ;/* Points are ordered by their distance from* the origin. */public compareTo(Object obj) {if( obj instanceof Point ) {Point p = (Point) obj ;double dist2 = x*x + y*y ;double p_dist2 = p.x*p.x + p.y*p.y ;return dist2 < p_dist2 ? -1 : 1 ;} else return -1 ;}...}public class Employee implements Comparable {String lastName ;String firstName ;/* Employees are ordered by name. */public compareTo(Object obj) {if( obj instanceof Employee ) {Employee empl = (Employee) obj ;int c = lastName.compareTo( empl.lastName ) ;/* If the last names match, compare first names. */if( c==0 ) {c = firstName.compareTo( empl.firstName ) ;}return c ;} else return -1 ;}...}The Wrapper ClassesGreat, now we can sort all kinds of objects. But how do wesort int?All of the primitive numeric types have wrapper classesthat implement Comparable: Integer, Double, Byte,etc.Integer i = new Integer(0) ;Integer j = new Integer(1) ;int c = i.compareTo(j) ;/* c=-1 */The Number ClassNumber is the abstract superclass of all the numericwrapper classes. It defines abstract methods forconverting between types.NumberByteShortInteger LongFloat DoubleThe Number Class: 2Number and its subclasses demonstrate a goodprogramming language design principle: try to implementthe features of the language in the language itself.Source code:int i = 2 ;String s = "i=" + i ;double x = i ;Compiler’s translation:Integer i = new Integer(2) ;String s = "i=".concat( i.toString() ) ;Double x = new Double( i.doubleValue() ) ;Summary: Abstract Classes andInterfaces•A class is a combination of data and operations onthat data.•An abstract class is a class that doesn’t fully define itsoperations.•An interface has no data. It only describes operations.An interface gives you the “what”—it’s up to theimplementor to provide the “how”.Interface Members and Modifiers•An interface may have fields, but they are all implicitlypublic, static and final. In other words, theymust be constants.•All of the methods in an interface are implicitlypublic and abstract.•An interface has either public or package scope. Thedefault is public.We typically skip the modifiers in an interface definition:we can assume they have the values above.Extending InterfacesYou can extend an interface, much like a class. Thesubinterface inherits all of the methods and constants ofits superinterface. An interface may extend more than oneother interface.public interface A { void foo() ; }public interface B { void bar() ; }public interface C extends A, B {void baz() ;/* C also contains foo() and bar().


View Full Document

NYU COMS W1007 - Interfaces and Abstraction

Download Interfaces and Abstraction
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Interfaces and Abstraction and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Interfaces and Abstraction 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?