interfaces and inner classes. what is an interface? what is “presented to the user”? the...
Post on 22-Dec-2015
215 Views
Preview:
TRANSCRIPT
Interfaces and Inner Interfaces and Inner ClassesClasses
What is an Interface?What is an Interface?
What is “presented to the user”?What is “presented to the user”? The public part of a class?The public part of a class? What is the substance of an interface?What is the substance of an interface?
Definition from Type TheoryDefinition from Type Theory
An interface is a “type”An interface is a “type” A type is a collection of method A type is a collection of method
specificationsspecifications A “contract”A “contract” The methods a user can expect to call uponThe methods a user can expect to call upon
That’s it!That’s it!
Separating Interface and Separating Interface and ImplementationImplementation
Why is it a Good Thing?Why is it a Good Thing? How is it done?How is it done? Example: Figures 1-5 in Jan00Example: Figures 1-5 in Jan00
Separation AnxietySeparation Anxiety
To fully separate interface from To fully separate interface from implementation, we separate the contract implementation, we separate the contract from the class(es) that implement(s) it!from the class(es) that implement(s) it!
Java InterfacesJava Interfaces
Similar to a class definitionSimilar to a class definition Used mainly for function prototypesUsed mainly for function prototypes
Abstract method declarationsAbstract method declarations Public and abstract by default!Public and abstract by default!
Can also include:Can also include: constants (static finals)constants (static finals) Nested classes and interfaces (covered later)Nested classes and interfaces (covered later)
Example: Next slide, Figure 6Example: Next slide, Figure 6
interface Stack{ void push(Object o) throws StackException; Object pop() throws StackException; Object top() throws StackException; int size();}
class FixedStack implements Stack{ // implementation unchanged // from Figure 1 …}
Advantage of InterfacesAdvantage of Interfaces(over inheritance)(over inheritance)
Any class that implements the interface Any class that implements the interface (i.e., provides the contract’s functionality) (i.e., provides the contract’s functionality) can be usedcan be used
Not constrained by subclassingNot constrained by subclassing
Implementation InheritanceImplementation Inheritance
What happens with What happens with extendsextends The subclass inherits implementation:The subclass inherits implementation:
Data and method bodiesData and method bodies You’re You’re stuckstuck with a particular implementation with a particular implementation
Interface InheritanceInterface Inheritance
A commitment to implement a contractA commitment to implement a contract No implementation is inheritedNo implementation is inherited Disadvantage:Disadvantage:
No code sharingNo code sharing Advantage:Advantage:
No code commitmentNo code commitment Freedom to implement any way you wantFreedom to implement any way you want
Interfaces vs. Abstract ClassesInterfaces vs. Abstract Classes
Use Abstract Classes when there is some Use Abstract Classes when there is some implementation to shareimplementation to share
In C++, an abstract class with only pure In C++, an abstract class with only pure virtual functions and no implementation virtual functions and no implementation behaves as an interfacebehaves as an interface
Multiple InheritanceMultiple Inheritance
What kind?What kind? Multiple inheritance of implementation is Multiple inheritance of implementation is
fraught with complexityfraught with complexity Virtual base classesVirtual base classes Dominance rulesDominance rules
Multiple inheritance of interfaces just Multiple inheritance of interfaces just means you must implement all the means you must implement all the methods in the hierarchymethods in the hierarchy And that’s all it meansAnd that’s all it means
class DynamicStack implements Stack, Persistent{ // implementation as in Figure 4 // PLUS need to implement read and write}
Interfaces as CapabilitiesInterfaces as Capabilities
Implements multiple interfacesImplements multiple interfaces Interface names are often adjectivesInterface names are often adjectives
They describe capabilitiesThey describe capabilities Example: AbleTest.javaExample: AbleTest.java
Sub- and Super-InterfacesSub- and Super-Interfaces
An interface can extend another interfaceAn interface can extend another interface The net result is just the union of all the The net result is just the union of all the
method specificationsmethod specifications
interface PersistentStack extends Stack, Persistent{}class DynamicStack implements PersistentStack {…}
Interfaces in the Java LibraryInterfaces in the Java Library
ComparableComparable::public int compareTo(Object x)public int compareTo(Object x)
Like C’s strcmp, returns:Like C’s strcmp, returns: Negative, if this < xNegative, if this < x Zero if this.equals(x)Zero if this.equals(x) Positive, if this > xPositive, if this > x
You decide how the ordering worksYou decide how the ordering works Used throughout the libraryUsed throughout the library
Comparing FractionsComparing Fractions
( 0, 0)
a cb d
ad bc
b d
⇒> >
:
:
compareTo( ) should return ad - bc
Interfaces in the Java LibraryInterfaces in the Java Library
CloneableCloneable For copying objectsFor copying objects Kind of dorkyKind of dorky
SerializableSerializable For automatic object storage and retrievalFor automatic object storage and retrieval
CollectionCollection Basic contract for collectionsBasic contract for collections
IteratorsIterators
A Design Pattern for traversing collectionsA Design Pattern for traversing collections java.util.Iterator interface:java.util.Iterator interface:public boolean hasNext( );public boolean hasNext( );public Object next( );public Object next( );public void remove( );public void remove( );
Collections typically implement IteratorCollections typically implement Iterator Benefit: Can have multiple iterators Benefit: Can have multiple iterators
simultaneouslysimultaneously Implemented as nested classesImplemented as nested classes
Iterator ExampleIterator Example
MySequence.javaMySequence.java An expandable array of ObjectAn expandable array of Object
MyIterator implements java.util.IteratorMyIterator implements java.util.Iterator MySequence.getIterator( ) returns a MySequence.getIterator( ) returns a
MyIterator objectMyIterator object
Issues with MySequence.javaIssues with MySequence.java
The class MyIterator has more visibility The class MyIterator has more visibility than it needsthan it needs Package access (we want private)Package access (we want private)
• Top-level classes can’t be private (or protected)Top-level classes can’t be private (or protected)
Clients only care about the Iterator Clients only care about the Iterator interface being implementedinterface being implemented They don’t care what type actually does itThey don’t care what type actually does it
Solution: nest MyIterator inside Solution: nest MyIterator inside MySequenceMySequence
Nested ClassesNested Classes
Can define classes and interfaces within Can define classes and interfaces within other classes and interfacesother classes and interfaces
Two flavors:Two flavors: Static (like nested classes in C++)Static (like nested classes in C++) Non-static (different!)Non-static (different!)
• Also called “inner classes”Also called “inner classes”
Can also define classes inside of a Can also define classes inside of a methodmethod ““local classes”local classes”
Static Nested ClassesStatic Nested Classes
Just like C++Just like C++ Just a scoping mechanismJust a scoping mechanism class A {class A {
static class B {…}static class B {…}}}A.B b = new A.B();A.B b = new A.B();
Inner ClassesInner Classes
Objects of inner classes only exist in Objects of inner classes only exist in connection with an instance of their connection with an instance of their containing class(es)containing class(es)
They have an invisible link to the object of They have an invisible link to the object of the containing classthe containing class
They can be declared with any access They can be declared with any access specifierspecifier Usually privateUsually private
Used a lot in AWT/SwingUsed a lot in AWT/Swing
Special SyntaxSpecial Syntax
Refer to variable in outer class:Refer to variable in outer class:Outer.this.varNameOuter.this.varName
Make an object of inner class:Make an object of inner class:Outer outer = new Outer();Outer outer = new Outer();Outer.Inner innerOuter.Inner inner = outer.new Inner();= outer.new Inner();
See page 230 of See page 230 of Core JavaCore Java
MySequence2.javaMySequence2.java
MyIterator is an inner classMyIterator is an inner class A MyIterator object has an implicit A MyIterator object has an implicit
MySequence object that “owns” itMySequence object that “owns” it Just like “this” is implicit in non-static methodsJust like “this” is implicit in non-static methods Any references to MySequence fields is Any references to MySequence fields is
resolved automaticallyresolved automatically ““data” == “MySequence.this.data”data” == “MySequence.this.data”
Local Inner ClassesLocal Inner Classes
Defined inside a methodDefined inside a method Not visible outside the methodNot visible outside the method
Can only access final locals in the Can only access final locals in the enclosing method enclosing method See p. 233 in See p. 233 in Core JavaCore Java
Example: MySequence3.javaExample: MySequence3.java
Anonymous Inner ClassesAnonymous Inner Classes
The name MyIterator is only used in one The name MyIterator is only used in one placeplace Hardly seems worth a separate name!Hardly seems worth a separate name!
Can define an unnamed class “on-the-fly” Can define an unnamed class “on-the-fly” instead in the return expression in instead in the return expression in MySequence.getIterator( )MySequence.getIterator( )
Can have no named constructorsCan have no named constructors Example: MySequence4.javaExample: MySequence4.java
Marker InterfacesMarker Interfaces
Interfaces with no definitions!Interfaces with no definitions! Merely to “color” or “tag” a classMerely to “color” or “tag” a class CloneableCloneable SerializableSerializable
Will cover in I/O sectionWill cover in I/O section
CloningCloning Meant to replace copy constructorsMeant to replace copy constructors
For “deep copies”For “deep copies” Somewhat problematic, but widely used!Somewhat problematic, but widely used!
Must Implement CloneableMust Implement Cloneable Must override Object.clone( )Must override Object.clone( )
But make it public! (It’s protected in Object)But make it public! (It’s protected in Object) Call super.clone() first! (To get the right type)Call super.clone() first! (To get the right type)
It is an error to call clone( ) for a class that does It is an error to call clone( ) for a class that does not implement Cloneablenot implement Cloneable Throws CloneNotSupportedExceptionThrows CloneNotSupportedException
Example: Figures 7-9Example: Figures 7-9
Cloning PolicyCloning Policy
1) Support it1) Support it As just describedAs just described
2) Let subclasses support it2) Let subclasses support it Don’t implement CloneableDon’t implement Cloneable But provide a protected clone if Object.clone() But provide a protected clone if Object.clone()
isn’t deep enoughisn’t deep enough 3) Forbid cloning3) Forbid cloning
Provide a clone( ) that unconditionally throws Provide a clone( ) that unconditionally throws CloneNotSupportedExceptionCloneNotSupportedException
top related