





















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






















Overview
Top-level vs. inner & nested
Iterator example Used inside outer class Used outside outer class
Syntax Uses for GUIs
Inner / Nested Classes
public class
MyInnerClass { … }
static public class
MyNestedClass { … }
Iterator iterator( ) { return
new Iterator( ) { … }
Inner Classes
Class defined in scope of another class May be named or anonymous
Outer & inner class
can directly access
each
other’s fields & methods (even if private)
Inner Class Link To Outer Class
Has association to an instance of outer class Must be instantiated with an enclosing instance Is
tied
to outer class object at moment of creation
(can not be changed)
MyList
MyList
MyIterator
MyIterator
MyIterator
Inner Classes
Private helper classes
Logical grouping of functionality Data hiding
Linkage to outer class
Inner class object
tied
to outer class object
Iterator
for Java Collections
ActionListener
for Java GUI widgets
(Problematic) MyIterator Design
public class MyIterator implements Iterator {
private MyList list;private int pos;MyIterator(MyList list) {
this.list = list;pos = 0; } public boolean hasNext() {
return pos < list.
size
} public Object next() {
return list.
a
[pos++];
MyIterator Design
Need to maintain reference to MyList Need to access
private
data in MyList
Define MyIterator as inner class for MyList
Instance of MyIterator tied to instance of MyList MyIterator methods can access private MyListfields
MyIterator objects can iterate through elements ofMyList
Instantiating Inner Class
Outer class method returns instance of inner class Used by Java Collections Library for Iterators
public class IC implements Iterator { … } public Iterator iterator() {
return
new IC();
// creates instance of IC
} MyList m = new MyList();Iterator it = m.iterator();
Using Inner Class
Inside
Outer Class
Use
a = new IC( );
to create instances of IC
a
is associated with the specific IC object referenced by
this
Using Inner Class
Outside
Outer Class
Use
a = b.new IC( );
to create instances of IC
a
is associated with a specific OC object
b
It is
very
rare for you to need to do this
Using Inner Class
Outside
Outer Class
// outer class
private int x = 2;
// don’t forget private
public class IC {
// inner class
int z = 4;public int getSum() {
return x + z; } } }
Accessing Outer Scope
// outer class
int x = 2;private class IC {
// inner class
int x = 6;private void getX() {
// inner class method
int x = 8;System.out.println(
x
// prints 8
System.out.println(
this.x
// prints 6
System.out.println(
OC.this.x
// prints 2
Method Invocations
Can be transparently redirected to outer instance
See if method can be resolved on inner object
If not, see if method can be resolved oncorresponding instance of outer object
If nested multiple levels, keep on looking