Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inner Classes 11/14/201828-Dec-04 inner_classes.ppt.

Similar presentations


Presentation on theme: "Inner Classes 11/14/201828-Dec-04 inner_classes.ppt."— Presentation transcript:

1 Inner Classes 11/14/ Dec-04 inner_classes.ppt

2 most classes we have seen are “top level”
Inner classes most classes we have seen are “top level” it is possible (and useful) to define a class inside another class the usual access modifiers (public, protected, private) can be used inner classes were not in Java 1.0 11/14/ Dec-04

3 you may encounter inner classes in two ways
member classes (also simply called “inner classes”) simply enclosed within another class typically not static often used as “listeners” anonymous inner classes also used as “listeners” but have no name syntax is ugly every class compiles to a separate .class file inner classes compile to files with a $ in their names 11/14/ Dec-04

4 a member class is an “ordinary” inner class
member classes a member class is an “ordinary” inner class class Outer { int n; class Inner { int ten = 10; void setNToTen( ) { n = ten; } } void setN ( ) { new Inner( ).setNToTen( ); } } 11/14/ Dec-04

5 member classes II member classes are often used to handle events:
Button b = new Button ("Click Me"); b.addActionListener (new Clicker( )); … class Clicker implements ActionListener { … } a member class can access the variables of the enclosing class this is what makes them so useful! declare them where you would declare a field or a method 11/14/ Dec-04

6 anonymous inner classes
anonymous inner classes are convenient for short code (typically a single method) b.addActionListener( anonymous inner class ); notice that no class name is If it had a name, it wouldn’t be anonymous 11/14/ Dec-04

7 example of anonymous inner class
an ActionListener is a Java-supplied interface for listening to Buttons and some other things the format (from the previous slide) is new Interface (args) { body } b.addActionListener ( new ActionListener( ) { public void actionPerformed (ActionEvent e) { System.out.println (“Ouch!”); } } ) ; like member classes, anonymous inner classes have full access to the fields and methods of the containing class however, Eclipse may not give you code-assist for them 11/14/ Dec-04

8 summary member (“inner”) classes anonymous classes
an ordinary class, just defined within another (anywhere a method or field could be placed) has full access to the variables of the enclosing class this is what makes them useful! anonymous classes inner classes without a class name useful for short Listeners used in only one place 11/14/ Dec-04

9 the end 11/14/ Dec-04


Download ppt "Inner Classes 11/14/201828-Dec-04 inner_classes.ppt."

Similar presentations


Ads by Google