Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inner Classes in Java. Overview Inner class – one class nested inside another – static (i.e. class) rarely if ever used – member (i.e. instance) – anonymous.

Similar presentations


Presentation on theme: "Inner Classes in Java. Overview Inner class – one class nested inside another – static (i.e. class) rarely if ever used – member (i.e. instance) – anonymous."— Presentation transcript:

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"); }


Download ppt "Inner Classes in Java. Overview Inner class – one class nested inside another – static (i.e. class) rarely if ever used – member (i.e. instance) – anonymous."

Similar presentations


Ads by Google