Nested Classes CompSci 230 S2 2015 Software Construction.

Slides:



Advertisements
Similar presentations
Introduction to classes Sangeetha Parthasarathy 06/11/2001.
Advertisements

Inner Classes. Nested Classes  An nested class is a class that is defined inside another class.  To this point we have only studied top-level classes.
Unit 08 & 091 Nested Classes Introduction Inner Classes Local Classes Anonymous Classes Exercises.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
1 Anonymous Classes A local class is a class that is defined in a block. This could be a method body, a constructor, a local block, a static initializer.
Access to Names Namespaces, Scopes, Access privileges.
Inner Classes. Lecture Objectives Learn about inner classes. Know the differences between static and non- static inner classes. Designing and using inner.
SCOPE & I/O CSC 171 FALL 2004 LECTURE 5. CSC171 Room Change Thursday, September 23. CSB 209 THERE WILL BE A (group) QUIZ! - topic: the CS department at.
OOP in Java – Inner Classes Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Unit 081 Introduction to Nested Classes Nested classes are classes defined within other classes The class that includes the nested class is called the.
Nested Classes OOP tirgul No Nested Classes Java allows you to define Nested Classes public class EnclosingClass { public int _dataMember = 7;
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
COMP More About Classes Yi Hong May 22, 2015.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Abstract and Nested Classes
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Agenda Scope of variables Comparable interface Location class in GridWorld homework.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
2-Dec-15 Inner Classes. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class.
2-Dec-15 Inner Classes By Alguien Soy. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
CS884 (Prasad)java11Extn1 Java 1.1 Extensions Nested classes static public/protected/private.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
An Advanced Code Pattern: Inner Classes CSE301 University of Sunderland Harry R. Erwin, PhD Half Lecture.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces and Inner Classes
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Basic Syntax อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 2.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Advanced Java class Nested Classes & Interfaces. Types of Nested Classes & Interfaces top-level nested –classes –interfaces inner classes –member –local.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Advanced Programming Practice Questions Advanced Programming. All slides copyright: Chetan Arora.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
N ESTED C LASSES -1. T YPES OF N ESTED C LASSES & I NTERFACES top-level nested classes interfaces inner classes member local named anonymous.
Today Enumerated Types - Summary. Start Nested Classes: Inner Classes, Local Classes, Anonymous Classes, Lambda Functions Next: Interfaces, Abstract Classes.
Inner Classes.
Topic: Inner Classes Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Reader, Dept. of IT 1.
Inner Classes 27-Dec-17.
CompSci 230 S Software Construction
Java Programming: Guided Learning with Early Objects
Lecture 5: Some more Java!
CompSci 230 S Programming Techniques
Nested class.
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
Java Programming Language
Overloading and Overriding
Inner Classes 29-Nov-18.
Namespaces, Scopes, Access privileges
Constructors, GUI’s(Using Swing) and ActionListner
Method of Classes Chapter 7, page 155 Lecture /4/6.
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Inner Classes 1-May-19.
CSE 341 Lecture 11 b closures; scoping rules
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Inner Classes.
Corresponds with Chapter 5
CSG2H3 Object Oriented Programming
Inner Classes 25-Oct-19.
Presentation transcript:

Nested Classes CompSci 230 S Software Construction

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

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

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

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

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

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

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

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 m2 InnerMember.Member in = m1.new Member(); Note: To instantiate an inner class, you must first instantiate the outer class 089

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

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

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

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

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

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

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

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

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

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