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

Cs 252 Inner Classes 07

The document discusses different types of nested and inner classes in Java. It describes: - Inner classes that are declared within another class and have access to the outer class's members and methods. They can be used to group related data and behavior. - Nested top-level classes that are static and follow the same rules as regular classes. They cannot access non-static members of the outer class. - Member classes that are non-static and have access to the outer class's non-static members using the 'this' keyword. They cannot be static. - Local classes declared within a method and cannot be public/protected. They can access final variables from the enclosing scope. - Anonymous classes that are local

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)
65 views31 pages

Cs 252 Inner Classes 07

The document discusses different types of nested and inner classes in Java. It describes: - Inner classes that are declared within another class and have access to the outer class's members and methods. They can be used to group related data and behavior. - Nested top-level classes that are static and follow the same rules as regular classes. They cannot access non-static members of the outer class. - Member classes that are non-static and have access to the outer class's non-static members using the 'this' keyword. They cannot be static. - Local classes declared within a method and cannot be public/protected. They can access final variables from the enclosing scope. - Anonymous classes that are local

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

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;

private static class StackNode {


private Object data; private StackNode next, prev;
public
public
data
}
public
public
}
public
public
public
public
public
}

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


StackNode( Object o, StackNode n ) {
= o; next = n;
StackNode getNext() { return next; }
Object getData() { return data; }

boolean isEmpty() { return tos == null; }


boolean isFull() { return false; }
void push( Object o ) { tos = new StackNode( o, tos ); }
void pop() { tos = tos.getNext(); }
Object top() { return tos.getData(); }
7

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
} }

void aMethod( int i ) {


= i;
//
= this.i;
//
= EnclosingClass.this.i;//
= j;
//

Assign
Assign
Assign
Assign

public void aMethod() {


MemberClass mem = new MemberClass();
mem.aMethod( 10 );
System.out.println( mem.i + mem.j );
}}

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

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

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

public static void main() {


EnclosingClass c = new EnclosingClass();
c.aMethod( 10, 50 ); }}

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

You might also like