(7) Inner Classes

(7) Inner Classes - 1 Java Inner Classes Department of...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 Java Inner Classes Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II 2 Overview Classes Top-level classes, versus inner classes and nested classes Inner classes Iterator example Used inside outer class Anonymous inner classes Syntax Uses for GUIs Nested classes 3 Java classes Top-level classes: Are declared inside a package Are visible throughout the package, and perhaps further Are normally declared in their own file Public classes must be defined in their own file This is not required for other classes Inner and nested classes are declared inside another class (possibly inside a method in that class) Are normally used only in the outer (enclosing) class, but can have wider visibility 4 Inner classes An inner class is a just a class that is defined in the scope of another class It may be named or anonymous An outer class and an inner class inside it can directly access each others fields and methods (even if private) 5 Inner class example public class OuterClass { private int x; private class InnerClass { private int y; void f() { x= 1; } // access private field } void g() { InnerClass ic= new InnerClass(); ic.y= 2; // access private field } } 6 Inner class link to outer class An inner class instance has an association to an instance of its outer class It must be instantiated with an instance of the enclosing outer class It is tied to the outer class object at the moment of creation (this can't be changed) MyList MyIterator MyIterator MyList MyIterator MyList 7 Why? Inner classes are useful for: Private helper classes Logical grouping of functionality Data hiding Linkage to outer class An inner class object is tied to an outer class object Examples: Iterator for Java Collections ActionListener for Java GUI widgets 8 Iterator example Consider this MyList class: public class MyList { private Object a; private int size; } Suppose we want to make MyList implement Iterable Just ignore generic types for simplicity We need to be able to return an Iterator 9 The Iterable interface The Iterable interface defines the method...
View Full Document

Page1 / 7

(7) Inner Classes - 1 Java Inner Classes Department of...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online