0% found this document useful (0 votes)
102 views31 pages

CS252InnerClasses07 PDF

This document discusses Java nested and inner classes. It covers several types of inner classes including nested top-level classes, member classes, and local classes. Nested top-level classes are declared static within another class, while member classes are not static and have access to enclosing instance variables. Member classes can only be instantiated if they have access to an enclosing class object. The document also discusses scoping rules and inheritance considerations for inner classes.

Uploaded by

Dhiraj Kumar Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views31 pages

CS252InnerClasses07 PDF

This document discusses Java nested and inner classes. It covers several types of inner classes including nested top-level classes, member classes, and local classes. Nested top-level classes are declared static within another class, while member classes are not static and have access to enclosing instance variables. Member classes can only be instantiated if they have access to an enclosing class object. The document also discusses scoping rules and inheritance considerations for inner classes.

Uploaded by

Dhiraj Kumar Jha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

CSDUniv.

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;

private static class StackNode {


private Object data; private StackNode next, prev;

public StackNode( Object o ) { this( o, null ); }


public StackNode( Object o, StackNode n ) {
data = o; next = n;
}
public StackNode getNext() { return next; }
public Object getData() { return data; }
}
public boolean isEmpty() { return tos == null; }
public boolean isFull() { return false; }
public void push( Object o ) { tos = new StackNode( o, tos ); }
public void pop() { tos = tos.getNext(); }
public Object top() { return tos.getData(); }
} 7
CSDUniv.ofCrete Fall2007

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 {

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
CSDUniv.ofCrete Fall2007

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 class DataStructure {


//create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];

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

//inner class implements the Iterator pattern


private class InnerEvenIterator {
//start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
//check if a current element is the last in the array
return (next <= SIZE);
}
public int getNext() {
//record an even element of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
} // end of inner class
public static void main(String s[]) {
//fill the array with integer values and print out only even numbers
DataStructure ds = new DataStructure();
DataStructure();
ds.printEven();
} Theoutputis:02468101214
} // end of DataStructure class

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";

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
public static void main() {
EnclosingClass c = new EnclosingClass();
19
c.aMethod( 10, 50 ); }}
CSDUniv.ofCrete Fall2007

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

new className( argumentList ) { classBody }


new interfaceName() { classBody }

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) {

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
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();
...

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 {
if(e.getSource()==button2) // do something
... }});
}});
30
CSDUniv.ofCrete Fall2007

Disadvantages

l DifficulttounderstandforinexperiencedJavaDevelopers
l Increasesthetotalnumberofclassesinyourcode
l TheDevelopertoolsdoesnotsupportmanythingsabouttheInner
Classes(e.g.Browsing)

l Manysecurityissuesaboutthissubject
uSomepeopleinsistnottouseInnerclassesbecausetheycanbe
usedfromanyonetoalterorextendthefunctionalityofthe
enclosingclassorsomeotherpackageclass
enclosingclassorsomeotherpackageclass

31

You might also like