DOC PREVIEW
UMD CMSC 132 - OOP in Java – Inner Classes

This preview shows page 1-2-21-22 out of 22 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

OOP in Java – Inner ClassesKinds of of ClassesKinds of nested/inner classesInner ClassesSlide 5Motivating ExampleMyIterator DesignSlide 8Slide 9Slide 10Method resolutionCreating/Referring to inner classesAccessing Outer ScopeAnonymous Inner ClassSyntax for anonymous inner classesMyList without anonymous inner classMyList with anonymous inner classNested classNested classesUsing inner classes in GUIsUsing inner class in a Count GUIWhat to noticeOOP in Java – Inner ClassesNelson Padua-PerezWilliam PughDepartment of Computer ScienceUniversity of Maryland, College ParkKinds of of ClassesTop level classesDeclared inside packageVisible throughout package, perhaps furtherNormally, although not always, declared in their own filepublic classes must be defined in their own fileNested and inner classesDeclared inside class (or method)can be visible only to outer class, or have wider visibilityKinds of nested/inner classesInner classdefined inside another classbut each instance of an inner class is transparently associated with an instance of the outer classmethod invocations can be transparently redirected to outer instanceAnonymous inner classesunnamed inner classesNested classdefined inside another classhas access to private members of enclosing classBut just a normal classInner ClassesDescriptionClass defined in scope of another classPropertyCan directly access all variables & methods of enclosing class (including private fields & methods)Examplepublic class OuterClass { public class InnerClass { ... }}Inner ClassesMay be named or anonymousUseful forLogical grouping of functionalityData hidingLinkage to outer classExamplesIterator for Java CollectionsActionListener for Java GUI widgetsMotivating ExampleMyListpublic class MyList { private Object [ ] a; private int size;}Want to make MyList implement Iterableskipping generic types at the momentneed to be able to return an IteratorMyIterator Designpublic 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 DesignProblemsNeed to maintain reference to MyListNeed to access private data in MyListSolutionDefine MyIterator as inner class for MyListMyIterator DesignCode 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++]; } }}Inner ClassesInner class instanceHas association to an instance of outer classMust be instantiated with an enclosing instanceIs tied to outer class object at moment of creation (can not be changed)MyList MyListMyIterator MyIterator MyIteratorMethod resolutionWhen resolving a method call on an unspecified objectfirst see if the method can be resolved on the inner object.If not, see if the method can be resolved on the corresponding instance of the outer objectIf nested multiple levels, keep on lookingCreating/Referring to inner classesAssume class A defines an inner class BInside instance methods of A, just use B as the type of references to the inner class and use new B(…) to create instancesnewly created B object associated with A object referenced by thisOutside of A, use A.B to name the inner classIf you need to create an instance of B associated with a specific A object a, outside of an instance method on ause a.new B()it is very rare for you to need to do thisAccessing Outer ScopeCodepublic class OC { // 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 } }}Anonymous Inner ClassDoesn’t name the classinner class defined at the place where you create an instance of it (in the middle of a method)Useful if the only thing you want to do with an inner class is create instances of it in one locationIn addition to referring to fields/methods of the outer class, can refer to final local variablesSyntax for anonymous inner classesusenew Foo() { public int one() { return 1; } public int add(int x, int y) { return x+y; } };to define an anonymous inner class that:extends class Foodefines methods one and addMyList without anonymous inner classCode 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++]; } }}MyList with anonymous inner classCode public class MyList implements Iterable { private Object [ ] a; private int size; public Iterator iterator() { return new Iterator () { private int pos = 0; public boolean hasNext() { return pos < size; } public Object next() { return a[pos++]; } }}Nested classDeclared like a standard inner class, except you say “static class” rather than “class”.For example:class LinkedList { static class Node { Object head; Node tail; } Node head; }Nested classesAn instance of an inner class does not contain an implicit reference to an instance of the outer classStill defined within outer class, has access to all the private fieldsUse if inner object might be associated with different outer objects, or survive longer than the outer objectOr just don’t want the overhead of the extra pointer in each instance of the inner objectUsing inner classes in GUIsjavax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndDisplayGUI(); } });button.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent evt) { System.out.println(“Button pushed”); } });Using inner class in a Count GUIclass Counter {int counter = 0;public Counter() { … final JLabel count = new JLabel("0"); JButton increment = new JButton("Increment"); increment.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent a) { counter++; count.setText(Integer.toString(counter));


View Full Document

UMD CMSC 132 - OOP in Java – Inner Classes

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download OOP in Java – Inner Classes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view OOP in Java – Inner Classes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view OOP in Java – Inner Classes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?