CompSci 230 S 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.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
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.
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.
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.
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.
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
Nested Classes CompSci 230 S Software Construction.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
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.
Topic: Classes and Objects
Sixth Lecture ArrayList Abstract Class and Interface
OOP: Encapsulation &Abstraction
Objects as a programming concept
Java Programming: Guided Learning with Early Objects
Lecture 5: Some more Java!
CompSci 230 S Programming Techniques
University of Central Florida COP 3330 Object Oriented Programming
Namespaces, Scopes, Access privileges
Nested class.
User-Defined Classes and ADTs
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
Java Programming Language
Overloading and Overriding
Classes & Objects: Examples
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.
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

CompSci 230 S1 2016 Software Construction Nested Classes

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

.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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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