Download presentation
Presentation is loading. Please wait.
Published byCarmella Edwards Modified over 9 years ago
1
Inner Classes in Java
2
Overview Inner class – one class nested inside another – static (i.e. class) rarely if ever used – member (i.e. instance) – anonymous most common – used in graphical programming – local rarely if every used
3
Member inner class member inner class – nested within another class – given a specific name – attributes and behaviors of nested class accessible to nesting class – attributes and behaviors of nesting class accessible to nested class – compiling creates additional class file outerclassname$innerclassname.class
4
Member inner class example //Example of Member Inner Class public class OuterClass { private InnerClass ic; public OuterClass () { ic = new InnerClass (); System.out.println("In OuterClass constructor"); } public static void main (String [] args) { OuterClass oc = new OuterClass(); oc.useInnerClass(); } public void useInnerClass() { ic.doSomething(); } private class InnerClass { private InnerClass () { System.out.println("In InnerClass constructor"); } private void doSomething() { System.out.println("I am doing something"); }
5
Anonymous inner class – nested within another class – not given a specific name – attributes and behaviors of classes are accessible to each other – used almost exclusively for tying events to widgets – compiling creates additional class file outerclassname$1.class (or 2, 3, etc.)
6
Anonymous inner class example //Example of Anonymous Inner Class class OuterClassWithAnonymousInner { public OuterClassWithAnonymousInner () { //Instantiation of the anonymous inner class // //The anonymous inner class is a subclass of InnerClass (see next slide) (new InnerClass () { public void doSomething () { System.out.println("I am doing something"); } }).doSomething(); System.out.println("In OuterClassWithAnonymousInner constructor"); } public static void main (String [] args) { new OuterClassWithAnonymousInner(); }
7
Anonymous inner class example continued from previous slide class InnerClass { InnerClass () { System.out.println("In InnerClass constructor"); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.