Presentation is loading. Please wait.

Presentation is loading. Please wait.

Nested Classes CompSci 230 S2 2015 Software Construction.

Similar presentations


Presentation on theme: "Nested Classes CompSci 230 S2 2015 Software Construction."— Presentation transcript:

1 Nested Classes CompSci 230 S2 2015 Software Construction

2 Agenda & Reading  Topics:  Static (Static Nested Classes)  Non-Static (Inner Classes)  Member Classes  MyStack with Inner Member Class  MyStack Without Nested class  Local Classes  Anonymous Classes  MyStack with Inner Anonymous  WindowAdapter  Reading  The Java Tutorial:  Nested Classes Nested Classes 082

3 Nested Classes  Definition:  A class defined inside another class  Some classes only make sense in the context of another enclosing class  Example  An Enumeration or Iterator object cannot exist by itself, only in association with a collection being enumerated/iterated  A GUI event handler cannot exist by itself, only in association with a GUI component it handles events for (Example: ActionListener)  We use nested classes to reflect and enforce the relationship between two classes  A nested class can be declared static or non-static  Static (Static Nested classes)  Non-Static (Inner class) public class MyRegularClass {... } class MyInnerClass {... } Outer class Inner class Inner class: Complete access to the fields and methods of its enclosing class, including those declared private.class created for the inner class: MyRegularClass$MyInnerClass.class 083

4 Static Nested Classes  A Static Nested Class:  can access static members and variables of its outer class  cannot refer to any instance variables  is associated with its enclosing/outer class public class MyOuter { int x; static int y = 100; public static class MyNested { public MyNested() { System.out.println(“constructor"); } public void instanceMethod() { System.out.println("Nested"); //System.out.println("x=" + x); System.out.println("y=" + y); } public void method() { MyNested n = new MyNested(); n.instanceMethod(); } Example: MyOuter.java Can access to static members Create a new instance Don’t need to instantiate an instance of the outer class, like the other static member variable (MyOuter.y) // called from any other classes MyOuter.MyNested n2 = new MyOuter.MyNested(); n2.instanceMethod(); // 1) within the outer class MyNested n1 = new MyNested(); n1.instanceMethod(); It creates an instance of the Nested class Outside the outer class, access it by its outer class name 084

5 Static Nested Classes  A Static Nested Class:  may be instantiated/accessed without an instance of the outer class  has the same behaviour as any static member of the outer class (associated with enclosing class not its instance) public class MyOuter {... public static class MyNested {... } public void method() { MyNested n = new MyNested(); n.instanceMethod(); } public void method2() { MyNested n1 = new MyNested(); n1.instanceMethod(); MyNested n2 = new MyNested(); n2.instanceMethod(); } MyOuter MyNested: nMyNested: n1MyNested: n2 // create an instance of the outer class MyOuter outer = new MyOuter(); outer.method(); outer.method2(); All instances of the Nested class are associated with the enclosing class 085

6 Accessing Methods and Fields  Example: Outer class: MyOuter1; nested class: MyNested1  In nested classes, you can refer to  Static variables of the outer class via  MyOuter1.variableNam e  Static methods via  g() or MyOuter1. g() public class MyOuter1 { private int x=1; private static int y=2; public void f() { //outer method MyNested1 b = new MyNested1(); System.out.println("b.x=" + b.x + ",b.y=" + b.y); b.f(); } public void g() { } public static void h() { } public static class MyNested1 { private int x = 10; private static int y=20; public void f() { System.out.println("x=" + x); System.out.println("y=" + y); System.out.println("MyOuter1.y=" + MyOuter1.y); h(); } public static void main(String[] args) { MyOuter1 a1 = new MyOuter1(); a1.f(); MyOuter1.MyNested1 b1 = new MyOuter1.MyNested1(); } 086

7 Inner Classes  Unlike a static nested class, every instance of an inner class requires an instance of the enclosing class  An instance of an inner class is effectively inside an existing instance of the outer class  Non-Static (Inner Classes)  Member Classes  A member class is defined within the body of a class  Local Classes  A local class is a class defined within a method  Anonymous Classes  A local class is declared implicitly by creating a variable of it OuterClassInstance InnerClassInstance public class MyRegularClass {... }...class MyInnerClass {... } 087

8 Member Classes  Definition  A member class is not declared static  A member class is defined within the body of a class  Rules  Member classes cannot declare static variables and methods  The member class has access to all instance and class variables and objects of the outer class or any other inner classes, including members declared private  The outer class has access to all the variables and methods in the inner class public class InnerMember { private int x; private static int y; public InnerMember() { x = y++; } private class Member { public void test() { System.out.println("x=" + x); x += 10; System.out.println("x=" + x); } … } Can access all instance and class variables public class Outer {... } class Inner {... } 088

9 Member Class Example class InnerMember { private int x; private static int y; public InnerMember() { x = y++; } private class Member { public void test() { System.out.println("x=" + x); x += 10; System.out.println("x=" + x); } public void test() { Member n = new Member(); n.test(); } m2.test(); Example: InnerMember.java m2 m1 y=0-> 1 0 InnerMember m1:x InnerMember m1 = new InnerMember(); m1.test(); m1 y=0-> 1 0->10 InnerMember m1:x :n InnerMember m2 = new InnerMember(); m2 y=0-> 1->2 0->10 InnerMember m1:x :n 1m2:x System.out.println(m1.x); System.out.println(m2.x); m2 y=0-> 1->2 0->10 InnerMember m1:x :n 1->11m2:x :n 10 11 m2 InnerMember.Member in = m1.new Member(); Note: To instantiate an inner class, you must first instantiate the outer class 089

10 Example: MyStack public class MyStack { private Vector items; public Enumeration enumerator() { return new MyStackEnumeration(); } class MyStackEnumeration implements Enumeration { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); }... } Can access the items object of an instance directly Example: stack_inner\MyStack.java 0810

11 MyStack – Without Inner Class public class MyStack { private Vector items; public Enumeration enumerator() { return new MyStackEnumeration(this); }... } MyStack.java Example: stack_noInner\MyStack.java public class MyStackEnumeration implements Enumeration { MyStack s; int currentItem; public MyStackEnumeration(MyStack s) { this.s = s; currentItem = s.size() - 1; } public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return s.elementAt(currentItem--); //add new method } MyStackEnumeration.java Stores a Stack instance in the MystackEnumerationClass 0811

12 Accessing Methods and Fields  Example: Outer class: A1; inner class: B1  In inner classes, you can refer to  variables of the outer class via A1.this.variableName  instance methods via A1.this.instanceMethod() or instanceMethod()  static methods via myOuterStaticMethod() or A1. myOuterStaticMethod() public class A1 { private int x=1; private static int y=100; public void f() { B1 b = new B1(); System.out.println("b.x=" + b.x); b.f(); } public class B1 { private int x = 10; //private static int y=100; public void f() { System.out.println("x=" + x); System.out.println("A1.x=" + A1.this.x + ",y=" + y); } public static void main(String[] args) { A1 a1 = new A1(); a1.f(); A1.B1 b1 = a1.new B1(); } Note: You can’t create inner class objects without first creating an outer class object 0812

13 Local Classes  A local class is a class defined within a method  A local class exists until end of that method/block only (hidden from everywhere else)  Use: if a class is needed only inside one method to do special work, and need not be visible anywhere else  Rules  Never declared with an access specifier-- scope is always restricted to the block in which they are declared (cannot be declared public, protected, private or static)  Cannot include static variables and methods  Can access the fields of the containing class and the local variables of the method they are declared in (if they are declared final) public class Outer { public void method() { } class Inner {... } 0813

14 Local Class Example public class InnerLocal { private final int i = 10; private String s = "Hello"; public void test() { final int j = 100; int w = 20; class LocalClass { public void test() { System.out.println("i=" + i); System.out.println("s=" + s); System.out.println("j=" + j); // System.out.println("w=" + w); } LocalClass l = new LocalClass(); l.test(); } public static void main(String[] args) { InnerLocal c = new InnerLocal(); c.test(); } i=10 s=Hello j=100 Example: InnerLocal.java Can access all instances fields Can access local final variables 0814

15 Anonymous Classes  Definition: a local class that is not given a name, but instead is declared implicitly by creating a variable of it  An object to be created using an expression that combines object creation with the declaration of the class  Anonymous classes are commonly used in AWT  Syntax  SuperType can be an interface (that the anonymous class implements) or a class (that the anonymous class extends)  The form of the new statement:  Declares a new anonymous class that extends a given class or implements a given interface,  creates a new instance of that class, and  returns it as the result of the statement  The class body can define methods but cannot define any constructors public class Outer { } new SuperType(constructor args) { //... class body }; 0815

16 Anonymous Class Example Example: stack_anonymous\MyStack.java public class MyStack { private Vector items; public Enumeration enumerator() { return new Enumeration() { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } }; } // additional code } Return an instance of a new class that implements the Enumeration interface public class Demo2 extends Frame { public Demo2() { setTitle("Demo 2"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }... Don’t need to put “implements WindowListener” here Return an instance of a new class that extends the WindowAdapter abstract class Example: Demo2.java 0816

17 Anonymous Class -> Member Class public class MyStack { private Vector items; public Enumeration enumerator() { return new Enumeration() { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } }; }... public class MyStack { private Vector items; public Enumeration enumerator() { return new MyStackEnumeration(); } class MyStackEnumeration implements Enumeration { int currentItem = items.size() - 1;... }... Interface: Enumeration Subclass: MyStackEnumeration 0817

18 Summary Type of Nested Class Applies ToDeclaredCan be Used Static MemberClasses and interfaces Inside a class as static By any class Member (non- static) ClassesInside a class (non-static) Within the member class Local (named)ClassesInside a methodWithin the method Anonymous (local unnamed) ClassesInside a method with no name Within the method 0818

19 Summary Type of Nested Class StructureVariable Visibility Static Membermay have instance or static variables/methods access only static outer variables and methods Member (non-static)no static methods or variables allowed access outer instance or static variables/methods Local (named)no static methods or variables allowed access – outer instance or static variables/methods – local final variables Anonymous (local unnamed) no static methods or variables allowed access – outer instance or static variables/methods – local final variables 0819


Download ppt "Nested Classes CompSci 230 S2 2015 Software Construction."

Similar presentations


Ads by Google