Presentation is loading. Please wait.

Presentation is loading. Please wait.

CompSci 230 S Software Construction

Similar presentations


Presentation on theme: "CompSci 230 S Software Construction"— Presentation transcript:

1 CompSci 230 S1 2016 Software Construction
Nested Classes

2 Agenda & Reading Topics: Reading 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 10

3 .class created for the inner class: MyRegularClass$MyInnerClass.class
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 { ... } Outer class Inner class: Complete access to the fields and methods of its enclosing class, including those declared private class MyInnerClass { ... } Inner class .class created for the inner class: MyRegularClass$MyInnerClass.class 10

4 Static Nested Classes A Static Nested Class:
Example: MyOuter.java 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(); Don’t need to instantiate an instance of the outer class, like the other static member variable (MyOuter.y) Can access to static members // called from any other classes MyOuter.MyNested n2 = new MyOuter.MyNested(); n2.instanceMethod(); // 1) within the outer class MyNested n1 = new MyNested(); n1.instanceMethod(); Outside the outer class, access it by its outer class name Create a new instance It creates an instance of the Nested class 10

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) All instances of the Nested class are associated with the enclosing class 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: n MyNested: n1 MyNested: n2 // create an instance of the outer class MyOuter outer = new MyOuter(); outer.method(); outer.method2(); 10

6 Accessing Methods and Fields
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(); Example: Outer class: MyOuter1; Nested class: MyNested1 In nested classes, you can refer to Static variables of the outer class via MyOuter1.variableName Static methods via g() or MyOuter1. g() 10

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 public class MyRegularClass { ... } ...class MyInnerClass { ... } InnerClassInstance 10

8 Can access all instance and class variables
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; … } public class Outer { ... } class Inner { ... } Can access all instance and class variables 10

9 Member Class Example m1 y=0-> 1 InnerMember m1:x m1 InnerMember
Example: InnerMember.java m1 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; Member n = new Member(); n.test(); InnerMember m1 = new InnerMember(); y=0-> 1 InnerMember m1:x m1 m1.test(); InnerMember y=0-> 1 m1:x 0->10 :n InnerMember m2 = new InnerMember(); m2 InnerMember y=0-> 1->2 m1:x 0->10 :n m2 m2:x 1 InnerMember y=0-> 1->2 m2.test(); m2 m1:x 0->10 :n m2 System.out.println(m1.x); System.out.println(m2.x); 10 11 m2:x 1->11 :n Note: To instantiate an inner class, you must first instantiate the outer class InnerMember.Member in = m1.new Member(); 10

10 Can access the items object of an instance directly
Example: MyStack Example: stack_inner\MyStack.java 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 10

11 MyStack – Without Inner Class
Example: stack_noInner\MyStack.java public class MyStack { private Vector items; public Enumeration enumerator() { return new MyStackEnumeration(this); } ... MyStack.java MyStackEnumeration.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 Stores a Stack instance in the MystackEnumerationClass 10

12 Accessing Methods and Fields
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; 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(); 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() Note: You can’t create inner class objects without first creating an outer class object 10

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 { ... } 10

14 Can access all instances fields Can access local final variables
Local Class Example Example: InnerLocal.java Can access all instances fields public class InnerLocal { private final int i = 10; private String s = "Hello"; public void test() { final int j = 100; int w = 20; class LocalClass { 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(); Can access local final variables i=10 s=Hello j=100 10

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 }; 10

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 Don’t need to put “implements WindowListener” here public class Demo2 extends Frame { public Demo2() { setTitle("Demo 2"); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); ... Return an instance of a new class that extends the WindowAdapter abstract class Example: Demo2.java 10

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--); }; ... Interface: Enumeration Subclass: MyStackEnumeration public class MyStack { private Vector items; public Enumeration enumerator() { return new MyStackEnumeration(); } class MyStackEnumeration implements Enumeration { int currentItem = items.size() - 1; ... 10

18 Summary Type of Nested Class Applies To Declared Can be Used
Static Member Classes and interfaces Inside a class as static By any class Member (non-static) Classes Inside a class (non-static) Within the member class Local (named) Inside a method Within the method Anonymous (local unnamed) Inside a method with no name 10

19 Summary Type of Nested Class Structure Variable Visibility
Static Member may 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) access – outer instance or static variables/methods – local final variables Anonymous (local unnamed) 10


Download ppt "CompSci 230 S Software Construction"

Similar presentations


Ads by Google