DOC PREVIEW
UMD CMSC 132 - Java Inner Classes

This preview shows page 1-2-3-24-25-26 out of 26 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 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 26 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 26 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 26 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 26 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 26 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1CMSC 132: Object-Oriented Programming IIJava Inner ClassesDepartment of Computer ScienceUniversity of Maryland, College Park2OverviewClassesTop-level vs. inner & nestedInner classesIterator exampleUsed inside outer classAnonymous inner classesSyntaxUses for GUIsNested classes3Java ClassesTop level classesDeclared inside packageVisible throughout package, perhaps furtherNormally declared in their own filePublic classes must be defined in their own fileNot required for other classesInner and nested classesDeclared inside class (or method)Normally used only in outer (enclosing) classCan have wider visibility4Inner / Nested ClassesInner classNested classAnonymous inner classExamplespublic class MyOuterClass {public class MyInnerClass { … }static public class MyNestedClass { … }Iterator iterator( ) { return new Iterator( ) { … } }}5Inner ClassesDescriptionClass defined in scope of another classMay be named or anonymousUseful propertyOuter & inner class can directly access each other’s fields & methods (even if private)6Inner ClassesExamplepublic class OuterClass { private int x;private class InnerClass { private int y; void foo( ) { x = 1; } // access private field}void bar( ) { InnerClass ic = new InnerClass( );ic.y = 2; // access private field}}7Inner Class Link To Outer ClassInner 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 MyIterator8Inner ClassesUseful forPrivate helper classesLogical grouping of functionalityData hidingLinkage to outer classInner class object tied to outer class objectExamplesIterator for Java CollectionsActionListener for Java GUI widgets9Iterator 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 Iterator10(Problematic) MyIterator 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++]; }…}11MyIterator DesignProblemsNeed to maintain reference to MyListNeed to access private data in MyListSolutionDefine MyIterator as inner class for MyListInstance of MyIterator tied to instance of MyListMyIterator methods can access private MyList fieldsMyIterator objects can iterate through elements of MyList12(Successful) MyIterator 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++]; }…}}13Instantiating Inner ClassHow to access instance of inner class?Common gimmickOuter class method returns instance of inner classUsed by Java Collections Library for IteratorsExample codepublic class MyList {public class IC implements Iterator { … }public Iterator iterator() {return new IC(); // creates instance of IC}}MyList m = new MyList();Iterator it = m.iterator();14Using Inner Class Inside Outer ClassAssume class OC defines an inner class ICInside methods of OC, just use IC normallyUse a = new IC( ); to create instances of ICa is associated with the specific IC object referenced by this15Using Inner Class Inside Outer ClassCodepublic class OC { // outer classprivate int x = 2;private class IC { // inner classprivate int y = 4;private int getSum() { return x + y; }}void bar( ) {IC z = new IC( ); // create new IC assoc. w/ thisz.getSum( ); // treat z like normal object}}16Accessing Outer ScopeCodepublic class OC { // outer classint x = 2;private class IC { // inner classint x = 6;private void getX() { // inner class methodint x = 8;System.out.println( x ); // prints 8System.out.println( this.x ); // prints 6System.out.println( OC.this.x ); // prints 2}}}17Method InvocationsMethod invocations on inner classCan be transparently redirected to outer instanceResolving method call on unspecified object1. See if method can be resolved on inner object2. If not, see if method can be resolved on corresponding instance of outer object3. If nested multiple levels, keep on looking18Anonymous Inner ClassDescription Inner class without nameDefined where you create an instance of itIn the middle of a methodReturns an instance of anonymous inner classUseful if the only thing you want to do with an inner class is create instances of it in one locationSyntaxnew ReturnType( ) { // unnamed inner classbody of class… // implementing ReturnType} ;19Anonymous Inner ClassCodepublic class MyList {public Iterator iterator( ) {return new Iterator( ) { // unnamed inner class… // implementing Iterator} ;}}MyList m = new MyList( );Iterator it = m.iterator( );20Example 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 thatExtends class Foo / implements interface FooDefines methods one & add21MyList With Explicit 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++]; }}}22MyList 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++]; }} ;}}23Support For Java GUIsGraphical User Interface (GUI) Java AWT & Swing librariesEvent-driven programming modelComponents may generate eventsE.g., ActionEvent, KeyEvent, MouseEventRequires event listeners to handle eventEvent listeners frequently implemented using anonymous classesUsed only in one locationImplements event listener interfaces24Using 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”);}} ) ;25Nested ClassDescriptionSimilar to inner class, but declared as static classNo link to an


View Full Document

UMD CMSC 132 - 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 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 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 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?