














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!















Defined inside another class But each instance of an inner class is transparentlyassociated with an instance of the outer class Method invocations can be transparently redirectedto outer instance
Unnamed inner classes
Defined inside another class Has access to private members of enclosing class But just a normal class
Class defined in scope of another class
Can directly access
all
variables & methods of
enclosing class (including private fields & methods)
public class InnerClass {
private Object [ ] a;private int size;
Skipping generic types at the moment Need to be able to return an Iterator
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++];
private Object [ ] a;private int size;public Iterator iterator() {
return new MyIterator(); } public class MyIterator implements Iterator {
private int pos = 0;public boolean hasNext() { return pos <
size
public Object next()
{ return
a
[pos++]; }
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
Newly created B object associated with A objectreferenced by this
Use a.new B() It is
very
rare for you to need to do this
// outer class
int x = 2;public class IC {
// inner class
int x = 6;public 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
Extends class Foo Defines methods one and add
MyList Without Anonymous Inner Class Code^ public class MyList implements Iterable {
private Object [ ] a;private int size;public Iterator iterator() {return new MyIterator();} public class MyIterator implements Iterator {
private int pos = 0;public boolean hasNext() { return pos <
size
public Object next()
{ return
a
[pos++]; }
Or just don’t want the overhead of the extra pointerin each instance of the inner object