java & inner classes

22
Java & Inner Java & Inner Classes Classes L. Grewe L. Grewe

Upload: maile-dixon

Post on 03-Jan-2016

50 views

Category:

Documents


0 download

DESCRIPTION

Java & Inner Classes. L. Grewe. Kinds of of Classes. Top level classes Declared inside package Visible throughout package, perhaps further Normally, although not always, declared in their own file public classes must be defined in their own file Nested and inner classes - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java  & Inner Classes

Java & Inner ClassesJava & Inner Classes

L. GreweL. Grewe

Page 2: Java  & Inner Classes

Kinds of of ClassesKinds of of Classes Top level classesTop level classes

• Declared inside packageDeclared inside package• Visible throughout package, perhaps furtherVisible throughout package, perhaps further• Normally, although not always, declared in Normally, although not always, declared in

their own filetheir own file public classes must be defined in their own filepublic classes must be defined in their own file

Nested and inner classesNested and inner classes• Declared inside class (or method)Declared inside class (or method)• can be visible only to outer class, or have can be visible only to outer class, or have

wider visibilitywider visibility

Page 3: Java  & Inner Classes

Kinds of nested/inner classesKinds of nested/inner classes Inner classInner class

• defined inside another classdefined inside another class• but each instance of an inner class is transparently but each instance of an inner class is transparently

associated with an instance of the outer classassociated with an instance of the outer class• method invocations can be transparently method invocations can be transparently

redirected to outer instanceredirected to outer instance Anonymous inner classesAnonymous inner classes

• unnamed inner classesunnamed inner classes Nested classNested class

• defined inside another classdefined inside another class• has access to private members of enclosing classhas access to private members of enclosing class• But just a normal classBut just a normal class

Page 4: Java  & Inner Classes

Inner ClassesInner Classes DescriptionDescription

• Class defined in scope of another classClass defined in scope of another class PropertyProperty

• Can directly access Can directly access allall variables & methods of variables & methods of enclosing class (including private fields & methods)enclosing class (including private fields & methods)

ExampleExamplepublic class OuterClass {public class OuterClass {

public class InnerClasspublic class InnerClass {{

......

}}

}}

Page 5: Java  & Inner Classes

Inner ClassesInner Classes

May be named or anonymousMay be named or anonymous Useful forUseful for

• Logical grouping of functionalityLogical grouping of functionality• Data hidingData hiding• Linkage to outer classLinkage to outer class

ExamplesExamples• IteratorIterator for Java Collections for Java Collections• ActionListenerActionListener for Java GUI widgets for Java GUI widgets

Page 6: Java  & Inner Classes

Motivating ExampleMotivating Example

MyListMyListpublic class MyList {public class MyList { private Object [ ] a;private Object [ ] a; private int size;private int size;}}

Want to make MyList implement Want to make MyList implement IterableIterable• skipping generic types at the momentskipping generic types at the moment• need to be able to return an Iteratorneed to be able to return an Iterator

Page 7: Java  & Inner Classes

MyIterator DesignMyIterator Designpublic class MyIterator implements Iteratorpublic class MyIterator implements Iterator {{ private MyList list;private MyList list; private int pos;private int pos; MyIterator(MyList list) {MyIterator(MyList list) { this.list = list;this.list = list; pos = 0;pos = 0; }} public boolean hasNext() { public boolean hasNext() { return pos < list.return pos < list.sizesize; ; } } public Object next() { public Object next() { return list.return list.aa[pos++]; [pos++]; }}}}

Page 8: Java  & Inner Classes

MyIterator DesignMyIterator Design

ProblemsProblems• Need to maintain reference to MyListNeed to maintain reference to MyList• Need to access Need to access privateprivate data in MyList data in MyList

SolutionSolution• Define MyIterator as inner class for Define MyIterator as inner class for

MyListMyList

Page 9: Java  & Inner Classes

MyIterator DesignMyIterator Design Code Code

public class MyList implements Iterable {public class MyList implements Iterable { private Object [ ] a;private Object [ ] a; private int size;private int size; public Iterator iterator() {public Iterator iterator() {

return new MyIterator(); return new MyIterator(); } }

public class MyIterator implements Iterator {public class MyIterator implements Iterator { private int pos = 0;private int pos = 0; public boolean hasNext() { return pos < public boolean hasNext() { return pos < sizesize; } ; } public Object next()public Object next() { return { return aa[pos++]; }[pos++]; } }}}}

Page 10: Java  & Inner Classes

Inner ClassesInner Classes Inner class Inner class instanceinstance

• Has association to an instance of outer Has association to an instance of outer classclass

• Must be instantiated with an enclosing Must be instantiated with an enclosing instanceinstance

• Is Is tiedtied to outer class object at moment to outer class object at moment of creation (can not be changed)of creation (can not be changed)

MyList MyList

MyIterator MyIterator MyIterator

Page 11: Java  & Inner Classes

Method resolutionMethod resolution

When resolving a method call on an When resolving a method call on an unspecified objectunspecified object• first see if the method can be resolved first see if the method can be resolved

on the inner object.on the inner object.• If not, see if the method can be resolved If not, see if the method can be resolved

on the corresponding instance of the on the corresponding instance of the outer objectouter object

• If nested multiple levels, keep on If nested multiple levels, keep on lookinglooking

Page 12: Java  & Inner Classes

Creating/Referring to inner Creating/Referring to inner classesclasses

Assume class A defines an inner class BAssume class A defines an inner class B Inside instance methods of A, just use B as the type Inside instance methods of A, just use B as the type

of references to the inner class and use new B(…) of references to the inner class and use new B(…) to create instancesto create instances• newly created B object associated with A object newly created B object associated with A object

referenced by thisreferenced by this Outside of A, use A.B to name the inner classOutside of A, use A.B to name the inner class If you need to create an instance of B associated If you need to create an instance of B associated

with a specific A object a, outside of an instance with a specific A object a, outside of an instance method on amethod on a• use a.new B()use a.new B()• it is it is veryvery rare for you to need to do this rare for you to need to do this

Page 13: Java  & Inner Classes

Accessing Outer ScopeAccessing Outer Scope CodeCode

public class OC {public class OC { // outer class// outer class int x = 2;int x = 2; public class IC {public class IC { // inner class// inner class int x = 6;int x = 6; public void getX() {public void getX() { // inner class method// inner class method

int x = 8;int x = 8; System.out.println( System.out.println( xx ); ); // prints 8// prints 8 System.out.println( System.out.println( this.xthis.x ); ); // prints 6// prints 6 System.out.println( System.out.println( OC.this.xOC.this.x ); ); // prints 2// prints 2 }} }}}}

Page 14: Java  & Inner Classes

Anonymous Inner ClassAnonymous Inner Class

Doesn’t name the classDoesn’t name the class inner class defined at the place where inner class defined at the place where

you create an instance of it (in the you create an instance of it (in the middle of a method)middle of a method)• Useful if the only thing you want to do with Useful if the only thing you want to do with

an inner class is create instances of it in one an inner class is create instances of it in one locationlocation

In addition to referring to fields/methods In addition to referring to fields/methods of the outer class, can refer to final local of the outer class, can refer to final local variablesvariables

Page 15: Java  & Inner Classes

Syntax for anonymous inner Syntax for anonymous inner classesclasses

useusenew Foo() {new Foo() { public int one() { return 1; } public int one() { return 1; } public int add(int x, int y) { return public int add(int x, int y) { return x+y; }x+y; } }; };

to define an anonymous inner class that:to define an anonymous inner class that:• extends class Fooextends class Foo• defines methods one and adddefines methods one and add

Page 16: Java  & Inner Classes

MyList without anonymous inner classMyList without anonymous inner class

Code Code public class MyList implements Iterable {public class MyList implements Iterable { private Object [ ] a;private Object [ ] a; private int size;private int size; public Iterator iterator() {public Iterator iterator() {

return new MyIterator(); return new MyIterator(); } }

public class MyIterator implements Iterator {public class MyIterator implements Iterator { private int pos = 0;private int pos = 0; public boolean hasNext() { return pos < public boolean hasNext() { return pos < sizesize; } ; } public Object next()public Object next() { return { return aa[pos++]; }[pos++]; } }}}}

Page 17: Java  & Inner Classes

MyList with anonymous inner MyList with anonymous inner classclass

Code Code public class MyList implements Iterable {public class MyList implements Iterable { private Object [ ] a;private Object [ ] a; private int size;private int size; public Iterator iterator() {public Iterator iterator() {

return new Iterator () return new Iterator () {{ private int pos = 0;private int pos = 0; public boolean hasNext() { return pos < public boolean hasNext() { return pos <

sizesize; } ; } public Object next()public Object next() { return { return aa[pos++]; }[pos++]; } }}}}

Page 18: Java  & Inner Classes

Nested classNested class Declared like a standard inner class, except Declared like a standard inner class, except

you say “static class” rather than “class”.you say “static class” rather than “class”. For example:For example:

class LinkedList {class LinkedList { static class Node { static class Node { Object head; Object head; Node tail; Node tail; } } Node head; Node head; } }

Page 19: Java  & Inner Classes

Nested classesNested classes

An instance of an inner class does not contain an An instance of an inner class does not contain an implicit reference to an instance of the outer classimplicit reference to an instance of the outer class

Still defined within outer class, has access to all Still defined within outer class, has access to all the private fieldsthe private fields

Use if inner object might be associated with Use if inner object might be associated with different outer objects, or survive longer than the different outer objects, or survive longer than the outer objectouter object• Or just don’t want the overhead of the extra Or just don’t want the overhead of the extra

pointer in each instance of the inner objectpointer in each instance of the inner object

Page 20: Java  & Inner Classes

Using inner classes in GUIsUsing inner classes in GUIs

javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {public void run() {

createAndDisplayGUI();createAndDisplayGUI();

}}

});});

button.addActionListener (new ActionListener() {button.addActionListener (new ActionListener() {

public void actionPerformed (ActionEvent evt) {public void actionPerformed (ActionEvent evt) {

System.out.println(“Button pushed”);System.out.println(“Button pushed”);

}}

});});

Page 21: Java  & Inner Classes

Using inner class in a Count Using inner class in a Count GUIGUI

class Counter {class Counter {int counter = 0;int counter = 0;

public Counter() { … final JLabel count = new JLabel("0");public Counter() { … final JLabel count = new JLabel("0"); JButton increment = new JButton("Increment"); JButton increment = new JButton("Increment"); increment.addActionListener( new ActionListener() { public increment.addActionListener( new ActionListener() { public

void actionPerformed(ActionEvent a) { counter++; void actionPerformed(ActionEvent a) { counter++; count.setText(Integer.toString(counter));count.setText(Integer.toString(counter));

repaint(); repaint(); }}); }});

Page 22: Java  & Inner Classes

What to noticeWhat to notice

Inside actionPerformed, we Inside actionPerformed, we referenced:referenced:• the value fieldthe value field• the display local variablethe display local variable• the the thisthis corresponding to the Counter corresponding to the Counter

when we invoked repaint()when we invoked repaint()• you can’t repaint an ActionListeneryou can’t repaint an ActionListener