comp 249 programming methodology chapter 13 interfaces & inner classes dr. aiman hanna...

42
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley Copyright © 2013 Aiman Hanna All rights reserved

Upload: scot-barber

Post on 04-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Comp 249 Programming Methodology

Chapter 13Interfaces & Inner Classes

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2013 Aiman Hanna

All rights reserved

InterfacesInterfaces An An interfaceinterface is something like an extreme case of an is something like an extreme case of an

abstract classabstract class However, However, an interface is not a classan interface is not a class It is a type that can be satisfied by any class that It is a type that can be satisfied by any class that

implements the interfaceimplements the interface The syntax for defining an interface is similar to that The syntax for defining an interface is similar to that

of defining a classof defining a class Except the word Except the word interfaceinterface is used in place of is used in place of classclass

An interface specifies a set of methods that any class An interface specifies a set of methods that any class that implements the interface must havethat implements the interface must have It contains method headings and constant It contains method headings and constant

definitions onlydefinitions only It contains no instance variables nor any complete It contains no instance variables nor any complete

method definitionsmethod definitions

13-2

InterfacesInterfaces

An interface serves a function similar An interface serves a function similar to a base class, though it is not a base to a base class, though it is not a base classclass Some languages allow one class to be Some languages allow one class to be

derived from two or more different base derived from two or more different base classesclasses

This This multiple inheritancemultiple inheritance is not allowed in is not allowed in JavaJava

Instead, Java's way of approximating Instead, Java's way of approximating multiple inheritance is through interfacesmultiple inheritance is through interfaces

13-3

InterfacesInterfaces An interface and all of its method headings An interface and all of its method headings

should be declared publicshould be declared public They cannot be given private, protected, or They cannot be given private, protected, or

package accesspackage access When a class implements an interface, it must When a class implements an interface, it must

make all the methods in the interface publicmake all the methods in the interface public Because an interface is a type, a method may Because an interface is a type, a method may

be written with a parameter of an interface be written with a parameter of an interface typetype That parameter will accept as an argument That parameter will accept as an argument

any class that implements the interfaceany class that implements the interface

13-4

The The OrderedOrdered Interface Interface

13-5

InterfacesInterfaces To To implement an interfaceimplement an interface, a concrete class , a concrete class

must do two things:must do two things:1.1. It must include the phraseIt must include the phrase

implements implements Interface_NameInterface_Nameat the start of the class definitionat the start of the class definition– If more than one interface is implemented, each is If more than one interface is implemented, each is

listed, separated by commaslisted, separated by commas

2.2. The class must implement The class must implement allall the method the method headings listed in the definition(s) of the headings listed in the definition(s) of the interface(s)interface(s)

Note the use of Note the use of ObjectObject as the parameter as the parameter type in the following examples type in the following examples

13-6

Implementation of an Implementation of an InterfaceInterface

13-7

Implementation of an Implementation of an InterfaceInterface

13-8

Abstract Classes Implementing Abstract Classes Implementing InterfacesInterfaces

Abstract classes may implement one or Abstract classes may implement one or more interfacesmore interfaces Any method headings given in the Any method headings given in the

interface are made into abstract methodsinterface are made into abstract methods

A concrete class must give definitions A concrete class must give definitions for all the method headings given in for all the method headings given in the abstract class the abstract class and the interfaceand the interface

13-9

An Abstract Class Implementing An Abstract Class Implementing an Interfacean Interface

13-10

Derived InterfacesDerived Interfaces

Like classes, an interface may be derived Like classes, an interface may be derived from a base interfacefrom a base interface This is called This is called extendingextending the interface the interface The derived interface must include the phraseThe derived interface must include the phrase

extends extends BaseInterfaceNameBaseInterfaceName

A concrete class that implements a A concrete class that implements a derived interface must have definitions for derived interface must have definitions for any methods in the derived interface as any methods in the derived interface as well as any methods in the base interfacewell as any methods in the base interface

13-11

Extending an InterfaceExtending an Interface

13-12

Pitfall: Interface Semantics Are Pitfall: Interface Semantics Are Not EnforcedNot Enforced

When a class implements an interface, the When a class implements an interface, the compiler and run-time system check the syntax compiler and run-time system check the syntax of the interface and its implementationof the interface and its implementation However, neither checks that the body of an However, neither checks that the body of an

interface is consistent with its intended interface is consistent with its intended meaningmeaning

Required semantics for an interface are normally Required semantics for an interface are normally added to the documentation for an interfaceadded to the documentation for an interface It then becomes the responsibility of each It then becomes the responsibility of each

programmer implementing the interface to programmer implementing the interface to follow the semanticsfollow the semantics

If the method body does not satisfy the specified If the method body does not satisfy the specified semantics, then software written for classes that semantics, then software written for classes that implement the interface may not work correctlyimplement the interface may not work correctly

13-13

Defined Constants in Defined Constants in InterfacesInterfaces

An interface can contain defined An interface can contain defined constants in addition to or instead of constants in addition to or instead of method headingsmethod headings Any variables defined in an interface must be Any variables defined in an interface must be

public, static, and finalpublic, static, and final Because this is understood, Java allows these Because this is understood, Java allows these

modifiers to be omittedmodifiers to be omitted Any class that implements the interface Any class that implements the interface

has access to these defined constantshas access to these defined constants

13-14

Pitfall: Inconsistent Pitfall: Inconsistent InterfacesInterfaces

In Java, a class can have only one base In Java, a class can have only one base classclass This prevents any inconsistencies arising from This prevents any inconsistencies arising from

different definitions having the same method different definitions having the same method headingheading

In addition, a class may implement any In addition, a class may implement any number of interfacesnumber of interfaces Since interfaces do not have method bodies, Since interfaces do not have method bodies,

the above problem cannot arisethe above problem cannot arise However, there are other types of However, there are other types of

inconsistencies that can ariseinconsistencies that can arise

13-15

Pitfall: Inconsistent Pitfall: Inconsistent InterfacesInterfaces

When a class implements two interfaces:When a class implements two interfaces: One type of inconsistency will occur if the One type of inconsistency will occur if the

interfaces have constants with the same name, interfaces have constants with the same name, but with different valuesbut with different values

Another type of inconsistency will occur if the Another type of inconsistency will occur if the interfaces contain methods with the same interfaces contain methods with the same name but different return typesname but different return types

If a class definition implements two If a class definition implements two inconsistent interfaces, then that is an inconsistent interfaces, then that is an error, and the class definition is illegalerror, and the class definition is illegal

13-16

The The SerializableSerializable InterfaceInterface

An extreme but commonly used An extreme but commonly used example of an interface is the example of an interface is the SerializableSerializable interface interface It has no method headings and no It has no method headings and no

defined constants: It is completely emptydefined constants: It is completely empty

It is used merely as a type tag that It is used merely as a type tag that indicates to the system that it may indicates to the system that it may implement file I/O in a particular wayimplement file I/O in a particular way

13-17

The The CloneableCloneable Interface Interface

The The CloneableCloneable interface is another interface is another unusual example of a Java interfaceunusual example of a Java interface It does not contain method headings or It does not contain method headings or

defined constantsdefined constants It is used to indicate how the method It is used to indicate how the method cloneclone (inherited from the (inherited from the ObjectObject class) class) should be used and redefinedshould be used and redefined

13-18

The The CloneableCloneable Interface Interface

The method The method Object.clone()Object.clone() does a does a bit-by-bit copy of the object's data in bit-by-bit copy of the object's data in storagestorage

If the data is all primitive type data or If the data is all primitive type data or data of immutable class types (such as data of immutable class types (such as StringString), then this is adequate), then this is adequate This is the simple caseThis is the simple case

The following is an example of a The following is an example of a simple class that has no instance simple class that has no instance variables of a mutable class type, and variables of a mutable class type, and no specified base classno specified base class So the base class is So the base class is ObjectObject

13-19

Implementation of the Method Implementation of the Method clone: clone: Simple CaseSimple Case

13-20

The The CloneableCloneable Interface Interface

If the data in the object to be cloned includes If the data in the object to be cloned includes instance variables whose type is a mutable instance variables whose type is a mutable class, then the simple implementation of class, then the simple implementation of cloneclone would cause a would cause a privacy leakprivacy leak

When implementing the When implementing the CloneableCloneable interface for interface for a class like this:a class like this: First invoke the First invoke the cloneclone method of the base method of the base

class class ObjectObject (or whatever the base class is) (or whatever the base class is) Then reset the values of any new instance Then reset the values of any new instance

variables whose types are mutable class variables whose types are mutable class typestypes

This is done by making copies of the instance This is done by making copies of the instance variables by invoking variables by invoking theirtheir clone methods clone methods

13-21

The The CloneableCloneable Interface Interface

Note that this will work properly Note that this will work properly only if the only if the CloneableCloneable interface is interface is implemented properly for the implemented properly for the classes to which the instance classes to which the instance variables belongvariables belong And for the classes to which any of And for the classes to which any of

the instance variables of the above the instance variables of the above classes belong, and so on and so forthclasses belong, and so on and so forth

The following shows an exampleThe following shows an example

13-22

Implementation of the Method Implementation of the Method clone: clone: Harder CaseHarder Case

13-23

Inner ClassesInner Classes

Inner classes are classes defined Inner classes are classes defined within other classeswithin other classes The class that includes the inner class The class that includes the inner class

is called the outer classis called the outer class There is no particular location where There is no particular location where

the definition of the inner class (or the definition of the inner class (or classes) must be place within the outer classes) must be place within the outer classclass

Placing it first or last, however, will Placing it first or last, however, will guarantee that it is easy to findguarantee that it is easy to find

13-24

Simple Uses of Inner Simple Uses of Inner ClassesClasses

An inner class definition is a member of the An inner class definition is a member of the outer class in the same way that the instance outer class in the same way that the instance variables and methods of the outer class are variables and methods of the outer class are membersmembers An inner class is local to the outer class An inner class is local to the outer class

definitiondefinition

The name of an inner class may be reused for The name of an inner class may be reused for something else outside the outer class something else outside the outer class definitiondefinition

If the inner class is private, then the inner If the inner class is private, then the inner class cannot be accessed by name outside the class cannot be accessed by name outside the definition of the outer classdefinition of the outer class

13-25

Simple Uses of Inner Simple Uses of Inner ClassesClasses

There are two main advantages to inner There are two main advantages to inner classesclasses They can make the outer class more self-They can make the outer class more self-

contained since they are defined inside a classcontained since they are defined inside a class Both of their methods have access to each Both of their methods have access to each

other's private methods and instance other's private methods and instance variablesvariables

Using an inner class as a helping class is Using an inner class as a helping class is one of the most useful applications of one of the most useful applications of inner classesinner classes If used as a helping class, an inner class If used as a helping class, an inner class

should be marked privateshould be marked private

13-26

Tip: Inner and Outer Classes Tip: Inner and Outer Classes Have Access to Each Other's Have Access to Each Other's

Private MembersPrivate Members Within the definition of a method of an inner class:Within the definition of a method of an inner class:

It is legal to reference a private instance variable of the It is legal to reference a private instance variable of the outer classouter class

It is legal to invoke a private method of the outer classIt is legal to invoke a private method of the outer class

Within the definition of a method of the outer classWithin the definition of a method of the outer class It is legal to reference a private instance variable of the It is legal to reference a private instance variable of the

inner class on an object of the inner classinner class on an object of the inner class It is legal to invoke a (nonstatic) method of the inner class It is legal to invoke a (nonstatic) method of the inner class

as long as an object of the inner class is used as a calling as long as an object of the inner class is used as a calling objectobject

So, within the definition of the inner or outer So, within the definition of the inner or outer classes, the modifiers classes, the modifiers publicpublic and and privateprivate are are equivalentequivalent

13-27

Class with an Inner ClassClass with an Inner Class

13-28

Class with an Inner ClassClass with an Inner Class

13-29

Class with an Inner ClassClass with an Inner Class

13-30

The The .class.class File for an File for an Inner ClassInner Class

Compiling any class in Java produces Compiling any class in Java produces a a .class.class file named file named ClassNameClassName.class.class

Compiling a class with one (or more) Compiling a class with one (or more) inner classes causes both (or more) inner classes causes both (or more) classes to be compiled, and produces two classes to be compiled, and produces two (or more) .class files(or more) .class files Such as Such as ClassNameClassName.class .class andand ClassName$InnerClassNameClassName$InnerClassName.class.class

13-31

Static Inner ClassesStatic Inner Classes A normal inner class has a connection A normal inner class has a connection

between its objects and the outer class between its objects and the outer class object that created the inner class objectobject that created the inner class object This allows an inner class definition to This allows an inner class definition to

reference an instance variable, or invoke a reference an instance variable, or invoke a method of the outer classmethod of the outer class

There are certain situations, however, There are certain situations, however, when an inner class must be staticwhen an inner class must be static If an object of the inner class is created within If an object of the inner class is created within

a static method of the outer classa static method of the outer class If the inner class must have static membersIf the inner class must have static members

13-32

Static Inner ClassesStatic Inner Classes Since a static inner class has no Since a static inner class has no

connection to an object of the outer class, connection to an object of the outer class, within an inner class methodwithin an inner class method Instance variables of the outer class Instance variables of the outer class

cannot be referencedcannot be referenced Nonstatic methods of the outer class Nonstatic methods of the outer class

cannot be invokedcannot be invoked

To invoke a static method or to name a To invoke a static method or to name a static variable of a static inner class static variable of a static inner class within the outer class, preface each with within the outer class, preface each with the name of the inner class and a dotthe name of the inner class and a dot

13-33

Public Inner ClassesPublic Inner Classes

If an inner class is marked If an inner class is marked publicpublic, then it , then it can be used outside of the outer classcan be used outside of the outer class

In the case of a nonstatic inner class, it In the case of a nonstatic inner class, it must be created using an object of the must be created using an object of the outer classouter class

BankAccount account = new BankAccount();BankAccount account = new BankAccount();BankAccount.Money amount = BankAccount.Money amount = account.newaccount.new Money("41.99"); Money("41.99");

Note that the prefix Note that the prefix account.account. must come must come before before newnew

The new object The new object amountamount can now invoke can now invoke methods from the inner class, but only from the methods from the inner class, but only from the inner classinner class

13-34

Public Inner ClassesPublic Inner Classes

In the case of a static inner class, the In the case of a static inner class, the procedure is similar to, but simpler procedure is similar to, but simpler than, that for nonstatic inner classesthan, that for nonstatic inner classes

OuterClass.InnerClass innerObject = OuterClass.InnerClass innerObject =

new OuterClass.InnerClass();new OuterClass.InnerClass();

Note that all of the following are Note that all of the following are acceptableacceptableinnerObject.nonstaticMethod();innerObject.nonstaticMethod();

innerObject.staticMethod();innerObject.staticMethod();

OuterClass.InnerClass.staticMethod();OuterClass.InnerClass.staticMethod();

13-35

Tip: Referring to a Method of the Tip: Referring to a Method of the Outer ClassOuter Class

If a method is invoked in an inner classIf a method is invoked in an inner class If the inner class has no such method, then it If the inner class has no such method, then it

is assumed to be an invocation of the method is assumed to be an invocation of the method of that name in the outer classof that name in the outer class

If both the inner and outer class have a If both the inner and outer class have a method with the same name, then it is method with the same name, then it is assumed to be an invocation of the method in assumed to be an invocation of the method in the inner classthe inner class

If both the inner and outer class have a If both the inner and outer class have a method with the same name, and the intent is method with the same name, and the intent is to invoke the method in the outer class, then to invoke the method in the outer class, then the following invocation must be used:the following invocation must be used:OuterClassNameOuterClassName.this..this.methodNamemethodName()()

13-36

Nesting Inner ClassesNesting Inner Classes

It is legal to nest inner classes within It is legal to nest inner classes within inner classesinner classes The rules are the same as before, but the The rules are the same as before, but the

names get longernames get longer Given class Given class AA, which has public inner class , which has public inner class BB, ,

which has public inner class which has public inner class CC, then the , then the following is valid:following is valid:A aObject = new A();A aObject = new A();

A.B bObject = aObject.new B();A.B bObject = aObject.new B();

A.B.C cObject = bObject.new C();A.B.C cObject = bObject.new C();

13-37

Inner Classes and Inner Classes and InheritanceInheritance

Given an Given an OuterClassOuterClass that has an that has an InnerClassInnerClass Any Any DerivedClassDerivedClass of of OuterClassOuterClass will will

automatically have automatically have InnerClassInnerClass as an inner as an inner classclass

In this case, the In this case, the DerivedClassDerivedClass cannot cannot override the override the InnerClassInnerClass

An outer class can be a derived classAn outer class can be a derived class An inner class can be a derived class alsoAn inner class can be a derived class also

13-38

Anonymous ClassesAnonymous Classes If an object is to be created, but there is no If an object is to be created, but there is no

need to name the object's class, then an need to name the object's class, then an anonymous classanonymous class definition can be used definition can be used The class definition is embedded inside the The class definition is embedded inside the

expression with the expression with the newnew operator operator Anonymous classes are sometimes used when Anonymous classes are sometimes used when

they are to be assigned to a variable of they are to be assigned to a variable of another typeanother type The other type must be such that an object The other type must be such that an object

of the anonymous class is also an object of of the anonymous class is also an object of the other typethe other type

The other type is usually a Java interfaceThe other type is usually a Java interface

13-39

Anonymous ClassesAnonymous Classes

13-40

Anonymous ClassesAnonymous Classes

13-41

Anonymous ClassesAnonymous Classes

13-42