Cs 252 Inner Classes 07
Cs 252 Inner Classes 07
ofCrete
Fall2007
JavaNestedandInnerClasses
JavaNestedandInnerClasses
Fall2007
CSDUniv.ofCrete
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)
Fall2007
CSDUniv.ofCrete
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
Fall2007
CSDUniv.ofCrete
Complication(2):Inheritance
l Almostanyformofinheritanceisallowed
uInnerclassisinheritedoutsideofthedefinedscope
class A {
class B { }
}
class C extends A.B { }
uInnerclasscanextenditsenclosingclass
class A {
class B extends A { }
}
4
Fall2007
CSDUniv.ofCrete
KindsofInnerClasses
l TherearedifferentkindsofinnerclassandbecameavailablewithJava
1.1.
uA)NestedtoplevelorStaticMember
levelorStaticMemberclass
uB)Memberclass
uC)Localclass
uD)Anonymousclass
Fall2007
CSDUniv.ofCrete
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
Fall2007
CSDUniv.ofCrete
LinkedStack
public class LinkedStack {
private StackNode tos = null;
Fall2007
CSDUniv.ofCrete
B/MemberClasses
l Amemberclassisanestedtoplevelclassthatis
levelclassthatisnotdeclaredstatic
l Thismeansthememberclasshasathis
Thismeansthememberclasshasathis referencewhichrefersto
theenclosingclassobject
l Memberclassescannotdeclarestatic
cannotdeclarestaticvariables,methodsornested
toplevelclasses
l Memberobjectsareusedtocreatedatastructuresthatneedtoknow
abouttheobjecttheyarecontainedin
abouttheobjecttheyarecontainedin
Fall2007
CSDUniv.ofCrete
Example
class Test {
private class Member {
public void test() {
i = i + 10;
System.out.println( i );
System.out.println( s );
}
}
public void test() {
Member n = new Member();
n.test();
}
private int i = 10;
private String s = Hello;
}
9
Fall2007
CSDUniv.ofCrete
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
Fall2007
CSDUniv.ofCrete
thisandMemberClasses
andMemberClasses
public class EnclosingClass {
private int i,j;
private class MemberClass {
private int i; public int j;
public
int a
int b
int c
int d
} }
Assign
Assign
Assign
Assign
param to a
member's i to b
top
top-level's
i to c
member's j to d
// is this a bug?
11
Fall2007
CSDUniv.ofCrete
newRevisited
Revisited
l Memberclassobjectscanonlybecreatediftheyhaveaccesstoan
enclosingclassobject
l Thishappensbydefaultifthememberclassobjectiscreatedbyan
instancemethodbelongingtoitsenclosingclass
l Otherwiseitispossibletospecifyanenclosingclassobjectusingthe
new operatorasfollows:
MemberClass b = anEnclosingClass.new
anEnclosingClass.new MemberClass();
12
Fall2007
CSDUniv.ofCrete
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
Fall2007
CSDUniv.ofCrete
SubclassingandInnerClasses
SubclassingandInnerClasses
14
Fall2007
CSDUniv.ofCrete
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
CSDUniv.ofCrete
Fall2007
l NotethattheInnerEvenIteratorclassrefersdirectlytothearrayOfInts
instancevariableoftheDataStructureobject.
instancevariableoftheDataStructureobject.
17
Fall2007
CSDUniv.ofCrete
C/LocalClasses
l Alocalclassisaclassdeclaredwithinthescopeofacompound
isaclassdeclaredwithinthescopeofacompound
statement,likealocalvariable
l Alocalclassisamemberclass,butcannotincludestaticvariables,
Alocalclassisamemberclass,but
methodsorclasses.Additionallytheycannotbedeclaredpublic,
methodsorclasses.Additionallytheycannotbedeclared
protected, private orstatic
static
l Alocalclasshastheabilitytoaccessfinal
Alocalclasshastheabilitytoaccessfinal variablesand
parametersintheenclosingscope
parametersintheenclosingscope
18
Fall2007
CSDUniv.ofCrete
LocalClassExample
public class EnclosingClass {
String name = "Local class example";
public void aMethod( final int h, int w )
int j = 20; final int k = 30;
class LocalClass {
public void aMethod() {
System.out.println( h );
// System.out.println( w ); ERROR w is not final
// System.out.println( j ); ERROR j is not final
System.out.println( k );
// System.out.println( i ); ERROR i is not declared yet
System.out.println( name); // normal member access
}}
LocalClass l = new LocalClass(); l.aMethod();
final int i = 10;
} // method end
19
Fall2007
CSDUniv.ofCrete
D/AnonymousClasses
l Ananonymousclassisalocalclass
localclassthatdoesnothaveaname
l Ananonymousclassallowsanobjecttobecreatedusinganexpression
thatcombinesobjectcreationwiththedeclarationoftheclass
combinesobjectcreationwiththedeclarationoftheclass
l Thisavoidsnamingaclass,atthecostofbeingabletocreateonlyone
Thisavoidsnamingaclass,atthecostofbeingabletocreate
instanceofthatanonymousclass
l ThisishandyintheAWT
20
Fall2007
CSDUniv.ofCrete
AnonymousClassSyntax
l Ananonymousclassisdefinedaspartofanewexpressionandmustbe
Ananonymousclassisdefinedaspartofa
asubclassorimplementaninterface
implementaninterface
new className( argumentList ) { classBody }
new interfaceName() { classBody }
thenewclasswillextend/implementthatclass/interface
thenewclasswillextend/implementthatclass/interface
l Theclassbodycandefinemethodsbutcannotdefineanyconstructors
l Therestrictionsimposedonlocalclassesalsoapply
21
Fall2007
CSDUniv.ofCrete
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 {
output:
public static void main(String arg[]){
My name is not specified
PRINTER pr = new PRINTER();
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
22
} // end of class
Fall2007
CSDUniv.ofCrete
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
boolean equals(Object o);
value);
int hashCode();
Object get(Object key);
}
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) {
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Object key = entry.getKey();
Object value = entry.getValue();
pw.println(key + " ->
> " + value);
}
}
26
CSDUniv.ofCrete
Fall2007
InnerClassesinAWTprogramming
l Counterandeventhandler(ActionListener
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,
theinvocationofactionPerformed
actionPerformed ofthelistenerobject
27
Fall2007
CSDUniv.ofCrete
WhyInnerClass?
l Eachinnerclasscanindependentlyinheritfromotherclasses
u outerclassinheritsfromoneclass
u innerclassinheritsfromanotherclass
l Theonlywaytogetmultipleimplementationinheritance
u Reusecodefrommorethanonesuperclass
l Makesdesignmoremodular
l Reducescomplexity
u Byencapsulation/informationhiding
Byencapsulation/informationhiding
28
Fall2007
CSDUniv.ofCrete
TheObjectOrientedadvantage
Orientedadvantage
l With InnerclassesyoucanturnthingsintoObjects
classesyoucanturnthingsintoObjects
l ForexampleinMemberclass:
uTheInnerclasstoSearchaTreeremovesthelogicofthe
classtoSearchaTreeremovesthelogicofthe
algorithmtofromanEnclosing
Enclosingclassmethod
uYoudontneedintimateknowledgeofthetreesdatastructureto
accomplishasearch
uFromanObjectOrientedpointofview,thetreeisatreeandnota
Orientedpointofview,thetreeisatreeandnota
searchalgorithm
29
Fall2007
CSDUniv.ofCrete
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();
...
public void
button1.addActionListener(
actionPerformed(ActionEvent e)
new java.awt.event.
{
ActionListener()
if(e.getSource()==button1)
{
{
public void actionPerformed
// do something
(java.awt.event.ActionEvent e)
}
{
else
// do something
if(e.getSource()==button2)
}});
}});
...
30
Fall2007
CSDUniv.ofCrete
Disadvantages
l DifficulttounderstandforinexperiencedJavaDevelopers
l Increasesthetotalnumberofclassesinyourcode
l TheDevelopertoolsdoesnotsupportmanythingsabouttheInner
Classes(e.g.Browsing)
l Manysecurityissuesaboutthissubject
uSomepeopleinsistnottouseInnerclassesbecausetheycanbe
usedfromanyonetoalterorextendthefunctionalityofthe
enclosingclassorsomeotherpackageclass
enclosingclassorsomeotherpackageclass
31