Escolar Documentos
Profissional Documentos
Cultura Documentos
ofCrete Fall2007
JavaNestedandInnerClasses
JavaNestedandInnerClasses
1
CSDUniv.ofCrete Fall2007
JavaInnerClasses
l Inner,orNested,classesarestandardclassesdeclaredwithinthescope
,classesarestandardclassesdeclaredwithinthescope
ofastandardtoplevelclass
u asamemberjustasfields/methods
u insideamethod(a.k.a.local/anonymous
anonymousclasses)
l Directaccesstomembersofitsenclosingdefinitions
u Programmingstylesimilartonestedfunctions
nestedfunctions
l Extensivelyusedineventdrivenprogramming
drivenprogramming(e.g.,AWT)
2
CSDUniv.ofCrete Fall2007
Complication(1):ScopingRules
l Directlyaccessiblemembersarein
arein
usuperclasses
uenclosingclasses
uevensuperclassesofenclosingclasses
class A {
Object f;
}
class B {
Object f;
class C extends A {
void m() {
f // which f?
}}}
3
CSDUniv.ofCrete Fall2007
Complication(2):Inheritance
l Almostanyformofinheritanceisallowed
uInnerclassisinheritedoutsideofthedefinedscope
class A {
class B { }
}
class C extends A.B { }
uInnerclasscanextenditsenclosingclass
class A {
class B extends A { }
}
4
CSDUniv.ofCrete Fall2007
KindsofInnerClasses
l TherearedifferentkindsofinnerclassandbecameavailablewithJava
1.1.
uA)NestedtoplevelorStaticMember
levelorStaticMemberclass
uB)Memberclass
uC)Localclass
uD)Anonymousclass
5
CSDUniv.ofCrete Fall2007
A/NestedTop
LevelClasses
class outer {
private static class NestedTopLevel {
normal class stuff
}
normal class stuff
}
l Nestedtoplevelclassesaredeclared
classesaredeclaredstaticwithinatoplevelclass
(sortoflikeaclassmember)
l Theyfollowthesamerulesasstandardclasses
u private static classescannotbeseenoutsidetheenclosing
class
u public static allowstheclasstobeseenoutside
6
CSDUniv.ofCrete Fall2007
LinkedStack
public class LinkedStack {
private StackNode tos = null;
B/MemberClasses
l Amemberclassisanestedtoplevelclassthatis
levelclassthatisnotdeclaredstatic
Thismeansthememberclasshasathis referencewhichrefersto
l Thismeansthememberclasshasathis
theenclosingclassobject
l Memberclassescannotdeclarestatic
cannotdeclarestaticvariables,methodsornested
toplevelclasses
l Memberobjectsareusedtocreatedatastructuresthatneedtoknow
abouttheobjecttheyarecontainedin
abouttheobjecttheyarecontainedin
8
CSDUniv.ofCrete Fall2007
Example
class Test {
thisRevisited
Revisited
l Tosupportmemberclassesseveralextrakindsofexpressionsare
severalextrakindsofexpressionsare
provided
u x = this.dataMember
dataMember isvalidonlyifdataMember
isvalidonlyifdataMember isan
instancevariabledeclaredbythe
instancevariabledeclaredbythememberclass,notif
dataMember belongstotheenclosingclass
u x = EnclosingClass.this.dataMember
EnclosingClass.this.dataMember allowsaccessto
dataMember thatbelongstotheenclosingclass
dataMember
l Innerclassescanbenestedtoanydepth
nestedtoanydepthandthethismechanism
canbeusedwithnesting
10
CSDUniv.ofCrete Fall2007
thisandMemberClasses
andMemberClasses
public class EnclosingClass {
private int i,j;
private class MemberClass {
private int i; public int j;
public void aMethod( int i ) {
int a = i; // Assign param to a
int b = this.i; // Assign member's i to b
int c = EnclosingClass.this.i;// Assign top
top-level's i to c
int d = j; // Assign member's j to d
} }
public void aMethod() {
MemberClass mem = new MemberClass();
mem.aMethod( 10 );
System.out.println( mem.i + mem.j ); // is this a bug?
}}
11
CSDUniv.ofCrete Fall2007
newRevisited
Revisited
l Memberclassobjectscanonlybecreatediftheyhaveaccesstoan
enclosingclassobject
l Thishappensbydefaultifthememberclassobjectiscreatedbyan
instancemethodbelongingtoitsenclosingclass
l Otherwiseitispossibletospecifyanenclosingclassobjectusingthe
new operatorasfollows:
MemberClass b = anEnclosingClass.new
anEnclosingClass.new MemberClass();
12
CSDUniv.ofCrete Fall2007
newRevisited(example)
Revisited(example)
public class EnclosingClass {
....code...
public class MemberClass {
...code
public void aMethod( int i ) {
...code
}
} // end of member class
} // end of enclosing class
class test{
public static void main(String a[]){
EnclosingClass ec = new EnclosingClass();
EnclosingClass.MemberClass b; // def of the variable's type
//b = new EnclosingClass.MemberClass(); // WILL NOT WORK
b = ec.new MemberClass(); // WORKS (the correcty way)
b.aMethod(7);
}}
13
CSDUniv.ofCrete Fall2007
SubclassingandInnerClasses
SubclassingandInnerClasses
14
CSDUniv.ofCrete Fall2007
Anotherexample
l Toseeaninnerclassinuse,let'sfirstconsideranarray.Inthe
followingexample,wewillcreateanarray,fillitwithintegervalues
andthenoutputonlyevenvaluesofthearrayinascendingorder.
valuesofthearrayinascendingorder.
TheDataStructureclassbelowconsistsof:
uTheDataStructureouterclass
outerclass,whichincludesmethodstoadd
anintegerontothearrayandprintoutevenvaluesofthearray.
uTheInnerEvenIteratorinnerclass
innerclass,whichissimilartoastandard
Javaiterator.Iteratorsareusedtostepthroughadatastructure
.Iteratorsareusedtostepthroughadatastructure
andtypicallyhavemethodstotestforthelastelement,retrievethe
currentelement,andmovetothenextelement.
uAmainmethodthatinstantiatesaDataStructureobject(ds)and
usesittofillthearrayOfIntsarraywithintegervalues(0,1,2,3,
etc.),thencallsaprintEvenmethodtoprintouttheevenvaluesof
etc.),thencallsaprintEvenmethodtoprintouttheevenvaluesof
arrayOfInts.
15
CSDUniv.ofCrete Fall2007
public DataStructure() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
//print out even values of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
16
CSDUniv.ofCrete Fall2007
l NotethattheInnerEvenIteratorclassrefersdirectlytothearrayOfInts
instancevariableoftheDataStructureobject.
instancevariableoftheDataStructureobject. 17
CSDUniv.ofCrete Fall2007
C/LocalClasses
l Alocalclassisaclassdeclaredwithinthescopeofacompound
isaclassdeclaredwithinthescopeofacompound
statement,likealocalvariable
l Alocalclassisamemberclass,butcannotincludestaticvariables,
Alocalclassisamemberclass,but
methodsorclasses.Additionallytheycannotbedeclaredpublic,
methodsorclasses.Additionallytheycannotbedeclared
protected, private orstaticstatic
Alocalclasshastheabilitytoaccessfinal variablesand
l Alocalclasshastheabilitytoaccessfinal
parametersintheenclosingscope
parametersintheenclosingscope
18
CSDUniv.ofCrete Fall2007
LocalClassExample
public class EnclosingClass {
String name = "Local class example";
D/AnonymousClasses
l Ananonymousclassisalocalclass
localclassthatdoesnothaveaname
l Ananonymousclassallowsanobjecttobecreatedusinganexpression
thatcombinesobjectcreationwiththedeclarationoftheclass
combinesobjectcreationwiththedeclarationoftheclass
l Thisavoidsnamingaclass,atthecostofbeingabletocreateonlyone
Thisavoidsnamingaclass,atthecostofbeingabletocreate
instanceofthatanonymousclass
l ThisishandyintheAWT
20
CSDUniv.ofCrete Fall2007
AnonymousClassSyntax
l Ananonymousclassisdefinedaspartofanewexpressionandmustbe
Ananonymousclassisdefinedaspartofa
asubclassorimplementaninterface
implementaninterface
thenewclasswillextend/implementthatclass/interface
thenewclasswillextend/implementthatclass/interface
l Theclassbodycandefinemethodsbutcannotdefineanyconstructors
l Therestrictionsimposedonlocalclassesalsoapply
21
CSDUniv.ofCrete Fall2007
UsingAnonymousClasses
class Person {
String name;
public String toString() { return "My name is "+ name;}
public Person(String nm) {name=nm;}
public Person() {this("not specified");}
}
class PRINTER{
void print(Object o){System.out.println(o.toString());}
o){System.out.println(o.toString());
}
public class AnonSimple {
public static void main(String arg[]){ output:
PRINTER pr = new PRINTER(); My name is not specified
Person person = new Person(); My name is Yannis
pr.print(person); My name is Nikos from Crete
pr.print(new Person("Yannis"));
pr.print(new Person("Nikos"){
public String toString() {return super.toString()+
" from Crete";}
}
); // end of method call
} // end of main
} // end of class 22
CSDUniv.ofCrete Fall2007
UsingAnonymousClasses
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainProg {
JFrame win;
public MainProg( String title ) {
win = new JFrame( title );
win.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit( 0 );
}});
}
public static void main( String args[] ) {
MainProg x = new MainProg( Simple Example );
}} 23
CSDUniv.ofCrete Fall2007
InnerClassesinDataStructures(LinkedList)
class LinkedList {
Element head;
class Element {
Object datum;
Element next;
public void Extract () {
if (head == this)
head = next;
else {
Element prevPtr = head;
while (prevPtr.next != this)
prevPtr = prevPtr.next;
prevPtr.next = next;
}
}
}
} 24
CSDUniv.ofCrete Fall2007
InnerClassesinDataStructures(Map)
public interface Map { public interface Entry {
int size(); Object getKey();
boolean isEmpty; Object getValue();
boolean containsKey(Object Object setValue(Object
key);
value);
boolean containsValue(Object
value); boolean equals(Object o);
Object get(Object key); int hashCode();
Object put(Object key, }
Object value); boolean equals(Object o);
Object remove(Object key); int hashCode();
void putAll(Map t); }
void clear();
public Set keySet();
public Collection values();
public Set entrySet();
25
CSDUniv.ofCrete Fall2007
InnerClassesinDataStructures(Map)
public void printMap(Map map, PrintWriter pw) {
26
CSDUniv.ofCrete Fall2007
InnerClassesinAWTprogramming
ActionListener)
l Counterandeventhandler(ActionListener
class Counter {
int x=0;
void regButton(Button b) {
b.addActionListener(
b.addActionListener(new Listener());}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e)
{ x++; }}}
uMethodregButton associatesalistenerwithagivenbutton
uEverytimethebuttonispressed,xwillbeincrementedthrough
Everytimethebuttonispressed,
actionPerformed ofthelistenerobject
theinvocationofactionPerformed
27
CSDUniv.ofCrete Fall2007
WhyInnerClass?
l Eachinnerclasscanindependentlyinheritfromotherclasses
u outerclassinheritsfromoneclass
u innerclassinheritsfromanotherclass
l Theonlywaytogetmultipleimplementationinheritance
u Reusecodefrommorethanonesuperclass
l Makesdesignmoremodular
l Reducescomplexity
u Byencapsulation/informationhiding
Byencapsulation/informationhiding
28
CSDUniv.ofCrete Fall2007
TheObjectOrientedadvantage
Orientedadvantage
l With InnerclassesyoucanturnthingsintoObjects
classesyoucanturnthingsintoObjects
l ForexampleinMemberclass:
uTheInnerclasstoSearchaTreeremovesthelogicofthe
classtoSearchaTreeremovesthelogicofthe
Enclosingclassmethod
algorithmtofromanEnclosing
uYoudontneedintimateknowledgeofthetreesdatastructureto
accomplishasearch
uFromanObjectOrientedpointofview,thetreeisatreeandnota
Orientedpointofview,thetreeisatreeandnota
searchalgorithm
29
CSDUniv.ofCrete Fall2007
TheCallBackAdvantage
public class SomeGUI extends public class SomeGUI extends JFrame
JFrame implements ActionListener {
{ ... button member declarations...
protected JButton button1; protected void buildGUI()
protected JButton button2; {
... button1 = new JButton();
protected JButton buttonN; button2 = new JButton();
...
Disadvantages
l DifficulttounderstandforinexperiencedJavaDevelopers
l Increasesthetotalnumberofclassesinyourcode
l TheDevelopertoolsdoesnotsupportmanythingsabouttheInner
Classes(e.g.Browsing)
l Manysecurityissuesaboutthissubject
uSomepeopleinsistnottouseInnerclassesbecausetheycanbe
usedfromanyonetoalterorextendthefunctionalityofthe
enclosingclassorsomeotherpackageclass
enclosingclassorsomeotherpackageclass
31