nested classes

43
Nested Classes 1 Nested Classes Learning Outcome List and distinguish between the different categories of nested classes List and explain four applications/benefits of nested classes Apply nested classes in applications development Introduction We start by introducing Nested Classes (NC), highlighting categories of NC and then outline the advantages of NC as they are used in Java We then briefly discuss and give example of each of the main categories of nested classes, namely static Member Classes Self-check Exercise 1 Non-static Member Classes Local Classes Anonymous Classes Self-check Exercise 2 Review Exercises We conclude the session with a set of review exercises

Upload: josiah-evans

Post on 03-Jan-2016

96 views

Category:

Documents


6 download

DESCRIPTION

Nested Classes. Learning Outcome List and distinguish between the different categories of nested classes List and explain four applications/benefits of nested classes Apply nested classes in applications development Introduction - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Nested Classes

Nested Classes 1

Nested Classes Learning Outcome

List and distinguish between the different categories of nested classes List and explain four applications/benefits of nested classes Apply nested classes in applications development

Introduction We start by introducing Nested Classes (NC), highlighting categories of NC

and then outline the advantages of NC as they are used in Java We then briefly discuss and give example of each of the main categories of

nested classes, namely static Member Classes Self-check Exercise 1 Non-static Member Classes Local Classes Anonymous Classes Self-check Exercise 2 Review Exercises

We conclude the session with a set of review exercises

Page 2: Nested Classes

Nested Classes 2

Introduction to Nested Classes

So far, our classes and interfaces were defined at top-level In our programs so far, we have defined classes and interfaces at the top level, which is the

package level

These top-level classes and interfaces are grouped into packages That is, …

Classes in the same package are accessible to each other We have also learnt that …

With access modifiers, classes can have inter-package access Furthermore, we can use access modifiers to make classes access other classes in different

packages

Newer versions of Java enable defining classes and interfaces inside other classes Starting from Java 1.1, classes and interfaces can be nested inside other classes to get additional

benefits Classes and interfaces defined inside other classes are called nested classes or nested interfaces

Page 3: Nested Classes

Nested Classes 3

Introduction to Nested Classes (cont’d)

There are four categories of nested classes in Java (which are): 1- static member classes and interfaces 2- Member classes 3- Local classes 4- Anonymous classes

Static member classes and interfaces are defined with the static keyword Static member classes and interfaces are nested classes and interfaces defined with the

static keyword

Member, local and anonymous classes are non-static, collectively called inner classes

Member classes are defined inside a class while local and anonymous classes are defined inside a block of Java code Local classes are typically defined inside methods.

We refer to both static and non-static classes as nested classes We use the term nested classes to refer to both static and non-static classes Some authors refer to static member classes as top-level, nested classes (an oxymoron!)

Inner classes

Page 4: Nested Classes

Nested Classes 4

Nested Classes at a Glance 1 class OuterClass{

2 static class StaticMemberClass {

3 // ...

4 }

5 static interface StaticMemberInterface{

6 void f();

7 }

8 class MemberClass {

9 // ...

10 }

11 public void myMethod(){

12 class LocalClass {

13 // ...

14 }

15 }

16 public StaticMemberInterface myMethod2(){

17 return new StaticMemberInterface(){

18 public void f(){}

19 };

20 }

21 }

Page 5: Nested Classes

Nested Classes 5

Nested Classes at a Glance: Transcript

A static member class defined with the static keyword An interface is always a static memberA member class inside another class. Note that it is not staticA local class defined inside the method myMethod()A method that returns an object of a class that implements StaticMemberInterfaceThe above line may be read: return an instance of a class that implements … interface. The class has no name but its definition follows after closing parenthesis after the interface name Notice the semi-colon after the closing brace that completes the class’s definition

Page 6: Nested Classes

Nested Classes 6

Why Nested Classes?

Why does Java introduce nested classes? Now that we have defined nested classes, one may ask, why does Java introduce

nested classes? Nested classes give additional support for: 1. Object-orientation

Separation of definition from functionality Because nested classes provide a means of separating definition from functionality. That is, nested

classes allow us to take logic out of an enclosing class and place it in a nested class (clearly an OO advantage)

For example, a data structures definition can be separate while its functionality (like methods needing to traverse the data structure) can be factored into a nested class

2. Code organization Nested classes are an additional means of providing namespace control and access control.

We can use nested classes to achieve more namespace control since the name of a nested class cannot conflict with the name of an another class in the same package

Furthermore, a private member class is hidden from classes in the same package. This level of access control cannot be achieved without inner classes.

Page 7: Nested Classes

Nested Classes 7

Why Nested Classes?

3. ‘Multiple inheritance’ (on top of single class and multiple interface inheritance) Recall that Java supports single class inheritance and multiple interface inheritance. With inner classes, a Java class can inherit from more than one abstract/concrete class

Because a single outer class can have several inner classes and Each inner class can independently inherit from an implementation in its own way

Therefore, interfaces and inner classes together provide a complete solution to the multiple (implementation) inheritance problem

4. Event-driven programming Recall that good software engineering requires us to make instance variables private But event handling methods typically need to access variables in another class to carryout event

handling properly. To access private members of a class we can

Define two public methods for each variable (a setter and a getter) or Define an inner class inside the class containing the private data

The use of inner classes to access private data provides a more concise and better solution

Page 8: Nested Classes

Nested Classes 8

static Member Classes

A static member class (or interface) is defined as a static member of another class

A static member class is a class (or interface) defined with the static specifier inside another classA member interface is implicitly static when the static keyword is omitted

static member classes are analogous to other static class members static member classes are analogous to the class fields and methods that are also declared static inside the class

Like a class method, a static member class is a top-level entity Like a class method, a static member class is not associated with any instance of the containing class (i.e., there is no this object)

A static member class has access to all static members of its outer classA static member class has access to all static members of its outer class, including private static membersstatic members of the outer class can also access static members of the static member class

static member classes can be defined only in top-level classes static member classes can be defined only inside top-level classes and also inside other static member classes and interfaces

Page 9: Nested Classes

Nested Classes 9

Introducing Our Working Example

Our working example involves a Course class containing students’ grades:class Course{

private double [] grades;

// …

}

There is an interface, MaxMin, with single method The bestAndWorst() method computes the best and worst grades in the course

interface MaxMin{

void bestAndWorst();

}

The class implementing MaxMin must have access to the grades arrayThe class that implements the MaxMin interface must have access to the grades arrayWith a nested class a neat solution is created whereby the grades array is accessed directly

To return the best and worst grades, we may define two methods… , one for each valueThis may require 2 traversals of the array since each method can return only one value

We define a class Pair that holds the best and worst gradesWith this class, a single method is required to return an instance of Pair that using a single traversal of the grades array

Page 10: Nested Classes

Nested Classes 10

Example 1: static Member Classes 1 import java.util.*;

2 class Course1{

3 private static double [] grades;

4 interface MaxMin{ void bestAndWorst();}

5 static class Pair implements MaxMin{

6 private double best;

7 private double worst;

8 public String toString(){

9 return "Best grade: "+best+"\nWorst grade: "+worst+"\n";

10 }

11 public void bestAndWorst(){

12 if(grades.length > 0){

13 best = grades[0];

14 worst = grades[0];

15 for(int i=1; i<grades.length; i++){

16 if (best < grades[i]) best = grades[i];

17 else if (worst > grades[i]) worst = grades[i];

18 }

19 }

20 }

21 }

Page 11: Nested Classes

Nested Classes 11

Example 1: static Member Classes (cont’d)22 Course1(int size){

23 grades = new double[size];

24 for(int i=0; i<size; i++)

25 grades[i] = 100*Math.random();

26 }

27 public MaxMin getPair(){

28 return new Pair();

29 }

30 }

31 public class Course1Test{

32 public static void main(String [] args){

33 Course1 c1 = new Course1(10);

34 Course1.MaxMin cs = new Course1.Pair();

35 cs.bestAndWorst();

36 System.out.println(cs);

37 }

38 }

Page 12: Nested Classes

Nested Classes 12

static Member Classes: Transcript

This is the grades array we introduced earlierAlso this is the MaxMin interface we already introducedThis is the Pair class implementing the MaxMin interfaceThe class pair has two private fields to hold the best and worst gradesThe Pair class overrides the inherited toString() methodThe bestAndWorst() method determines the best and worst grades and store them in the two instance variables of the Pair classIt is assumed that the first element in the array is the best and the worst at the same timeThese values are updated as he remaining elements in the array are inspectedA constructor of the COurse1 class that initializes the grades array with ten random valuesEach value is a number between 0 and 100getPair() method is an instance method of the Couse1 class that returns an instance of the Pair class

Page 13: Nested Classes

Nested Classes 13

static Member Classes: Transcript

Class Course1Test is the driver class used to test the Course1 classThe statement at line xy creates an object of type PairObserve this object-creation expression carefully. In particular the name of the class Pair is prefixed with the name of its outer class, Course1This is what we mean by saying that the name of the nested class Pair cannot conflict with the name of another class in the same packageThe instance of the Pair class is now used to compute the best and worst gradesFinally the program prints the values of the best and worst grades found

MCQWhat is the significance of the line: Course1 c1 = new Course1(10);

not needednecessary to initialize the array

Page 14: Nested Classes

Nested Classes 14

static Member Classes: Transcript

Notice the full name of the nested classes and interfaces in the object-creation statement inside the main() method Notice that when this program is compiled, four .class files will be generated:

Course1.classMaxMin.classCourse1.Pair.classCourse1Test.class

An object of a static inner class does not have a reference to the outer class object that generated it.The following example demonstrates

The use of a static member class to hide a class named PairA static member class accessing the private static member of its outer classA static member class implementing an interface

Page 15: Nested Classes

Nested Classes 15

Quiz 1(1) Select all correct answers in the following. Top-level classes and interfaces

(1) Are always in the same package

(2) Are always defined at top-level

(3) Where not available before Jva 1.1

(4) Do not use access modifiers

(2) Which of the following statements about nested classes are correct?

(1) Static member classes can access all other members of the outer class

(2) A static member class must be defined as the first member of its enclosing class

(3) All non-static classes are called inner classes

(4) An outer class of a static member class must also be static

(3) Using the MaxMin interface in Example 1, the statement MaxMin [] pairs = new MaxMin[10]

(1) Is invalid because MaxMin is an interface

(2) Is valid and creates ten objects

(3) Is valid and creates eleven objects

(4) Is valid and creates only one object

Page 16: Nested Classes

Nested Classes 16

Member Classes

A member class is defined as a non-static member of another classA member class is a class that is defined as a non-static member of another class

A member class is analogous to an instance field or instance method Like other instance members, a member class can have any access modifier

That is a member class can be public, default, protected or private

Every instance of a member class is linked with an instance of the containing class This means that the code for a member class has access to all the instance fields and instance methods of the containing class (including private ones) Instance of a containing class needs not be associated with an instance of the member class

Member classes cannot have static fields, static methods or static classes (except static final fields)

Because static fields, methods and class are top-level constructs not associated with any particular object whileEvery member object is associated with an object of its enclosing class

Page 17: Nested Classes

Nested Classes 17

Member Classes (cont’d)

Interfaces cannot be defined as member classes. Why? Because an interface cannot be instantiated and, therefore, if it is a member class no instance of the interface can be created to associate with an object of the enclosing classNote that a nested interface is explicitly or implicitly static, making it a static member class

The name of a member class, unlike fields and methods, must be different from that of any containing class or package

Page 18: Nested Classes

Nested Classes 18

Example 2: Member Classes 1 protected class Pair implements MaxMin{

2 public void bestAndWorst(){

3 if(grades.length > 0){

4 best = grades[0];

5 worst = grades[0];

6 for(int i=1; i<grades.length; i++){

7 if (best < grades[i]) best = grades[i];

8 else if (worst > grades[i]) worst = grades[i];

9 }

10 }

11 }

12 }

13 public class Course2Test{

14 public static void main(String [] args){

15 Course2 c2 = new Course2(10);

16 Course2.MaxMin cs = c2.new Pair();

17 cs.bestAndWorst();

18 System.out.println(cs);

19 }

20 }

Page 19: Nested Classes

Nested Classes 19

Example 2: Transcript This class is the same as in Example 1 except that in this case the class is non-static and has the protected access modifier

Variables and the toString() method hidden for brevity

The test class is also the same as in Example 1 except line 16 which we now discuss

Notice carefully how an object of Pair is created using the the reference of the outer class Course2.

This what we mean by saying that an object of a member class is always created under using a reference of an object of the enclosing class

Page 20: Nested Classes

Nested Classes 20

Example 2: Transcript (cont’d) Notice how class Pair accesses the private array grades of its enclosing class

Where ever class Pair is used inside Course2, its short name can be used instead of its fully-qualified name

Inside class Course2Test, Pair is known only using its fully-qualified name Compare the object-creation statements in Course1Test and Course2Test:

An object of static member class does not require an object of its enclosing class (Course1Test), whileAn object of member class requires an object of its enclosing class to be created (Course2Test)

Page 21: Nested Classes

Nested Classes 21

Can We Override Member Classes? Transcript

From our discussions, member classes have much in common with instance methods Since instance methods can be overridden, can we also override member classes?

A good question to investigate is, since instance methods can be overridden, can we also override member classes?This example attempts to answer this question

This example defines a class Course2 which contains a member class called PairThe constructor of class Course2 simply displays a message and then creates an object of class PairThe constructor of class Pair consists of a simple print statementThe test class in this program, OverridingMemberClass, is very similar to class Course2: it extends class Course2 and defines a member class Pair as in its parent class Course2 When the program is executed, we see that the constructor of class Pair inside Course2 is executed rather than the constructor of class Pair inside the subclassThis shows that extending an outer class and redefining its member class does not amount to overriding the inherited member class

Notice that the same behavior is obtained when you attempt to “override” a static method from a super class

Page 22: Nested Classes

Nested Classes 22

Example 3: Can We Override Member Classes? 1 class Course2{ 2 public Course2(){ 3 System.out.println("Couse2 constructor."); 4 new Pair(); 5 } 6 protected class Pair { 7 public Pair(){ 8 System.out.println("Course2.Pair constructor."); 9 } }10 }11 class OverridingMemberClass extends Course2{12 public OverridingMemberClass(){13 System.out.println("OverridingMemberClass constructor.");14 }15 protected class Pair {16 public Pair(){17 System.out.println("OverridingMemberClass.Pair constructor."); }18 }19 public static void main(String [] args){20 new OverridingMemberClass();21 }22 }

Page 23: Nested Classes

Nested Classes 23

Example 4: Using this in Member Classes

As an object of a member class requires a reference of its enclosing class, the this reference is applicable inside member classes

Notice that this is similar to the fact that the this reference is applicable inside instance methods while it is not applicable inside static methods

From within an instance of a member class we can refer to two objectsNote that from within an instance of a member class we have two objects that we can refer to using the this reference

How do we distinguish the two objects?That is, how do we distinguish an instance of the member class from that of the enclosing class using the this reference?

The next example demonstrates how this can be doneThis is done simply as indicated:

To refer to the outer class object, use the notation OuterClass.thiswhen the this reference is used without a prefix, it refers to the member class object.

Note that in reality, The compiler automatically passes the this reference to the member object through the constructor of the member class. Furthermore, the compiler automatically inserts a method that it uses to access each private field inside the enclosing class.

Page 24: Nested Classes

Nested Classes 24

Example 4: Keyword this in Member Classes

// code omitted

1 public void bestAndWorst(){

2 if(Course2.this.grades.length > 0){

3 this.best = Course2.this.grades[0];

4 this.worst = Course2.this.grades[0];

5 for(int i=1; i<grades.length; i++){

6 if (best < grades[i]) best = grades[i];

7 else if (worst > grades[i]) worst = grades[i];

8 }

9 }

10 }

// code omitted

Page 25: Nested Classes

Nested Classes 25

Example 5: Extending Member Classes

Example 3 shows that member classes are inherited but cannot be overriddenIn Example 3 we show that we can extend an outer class and inherit its member classes but cannot override the inherited member classes

Example 4 shows that a member class receives a reference of an object of the enclosing class implicitly

In Example 4 we show that a reference of an object of an enclosing class is implicitly passed to the object of a member class through the constructor(s) of the member class

We will use this example to answer the questions: Can a member class be extended alone?

Can we extend a member class without extending its outer class? Is a member class a subclass of its enclosing class? How are constructors of subclasses of member classes written?

Constructors of subclasses of member classes must be written to ensure that the member class is correctly initialized and also to ensure that the enclosing classes of the member class are correctly initialized.

The complete example follows on the next page

Page 26: Nested Classes

Nested Classes 26

Example 5: Extending Member Classes 1 class Course2{ 2 public Course2(){ 3 System.out.println("Couse2 constructor."); 4 } 5 protected class Pair { 6 public Pair(){ 7 System.out.println("Pair constructor."); 8 } 9 }10 }11 class ExtendingMemberClass extends Course2.Pair{12 public ExtendingMemberClass(Course2 c2){13 c2.super();14 System.out.println("ExtendingMemberClass constructor.");15 }16 public static void main(String [] args){17 Course2 c2 = new Course2();18 //Course2 c2 = new Course2().new Pair();19 new ExtendingMemberClass(c2);20 }21 }

Page 27: Nested Classes

Nested Classes 27

Example 5: Part Trancript Class Course2 in this example is very similar to that in Example 3.

It should require no additional explanation.

The class ExtendingMemberClass is extending the member class Pair … as we can see

Defining a constructor for a subclass of a member class is not straight forward: Recall that an object of an enclosing class implicitly passes a reference to itself to the object of its member class The implicit reference received must be made explicit in subclasses

If the member class is extended this implicit reference must be made explicit in the derived class

An explicit reference of the enclosing class must be explicitly passed to the constructor of the class extending the member class

Therefore in the constructor of class ExtendingMemberClass, we pass an explicit reference of an object of Course2 This makes it possible for correct initializations to take place through the constructor of class ExtendingMemberClass.

Note that although Pair is not a subclass of Course2 An object of Course2 must be initialized before that of Pair and

as expected, Pair is initialized before its subclass ExtendingMemberClass

Page 28: Nested Classes

Nested Classes 28

Example 5: Transcript (cont’d)

In summary, this example has shown that member classes can be extended without extending their enclosing class member classes are not subclasses of their enclosing classes constructors to subclasses of member classes must receive explicit reference of an object of the enclosing class of the member class as illustrated

Page 29: Nested Classes

Nested Classes 29

JVM View of Member Classes No changes were made to the JVM to support nested classes

When inner classes were introduced, no changes where made to the JVM and the old JVM supports them automatically Member classes are compiled to class files just like top-level classes but

Before nested classes, classes (top-level) can have only public or package visibilityWith nested classes, member classes can have any access modifier

As we mentioned earlier a member class can have any access modifier: public, default, protected or

private How does the JVM treat member classes with protected and private modifiers?

Since the JVM was not changed how does it treat …The JVM treats protected and private member classes to have public and package visibility respectively Note that the JVM cannot enforce these access control modifiers; the compiler does

Although the JVM cannot enforce these access control modifiers, the modifiers are noted in the class fileThis allows any conforming Java compiler to enforce the access modifiers and prevent member classes from being accessed in unintended ways

Page 30: Nested Classes

Nested Classes 30

Local Classes

When a class name is used once it can be defined locallyWhen a class name is known to be used only once, within a single method of its containing class, then it can be defined locally within a method

A local class is defined within a block of Java codeA local class is a class defined within a block of Java code

Like a local variable a local class is visible only within its enclosing blockFurthermore, local classes cannot be declared public, protected, private or static

Local classes share many of the features of member classes Local classes are not member classes but they share many of the features of member classes since they are defined within an enclosing class

An instance of a local class is associated with an instance of its enclosing class Like a member class, an instance of a local class is associated with an instance of its containing class Furthermore, an instance of a local class access final variables in its enclosing block

Local classes can be completely hidden in their containing block Local classes have the added advantage that they are completely hidden inside their enclosing method or block

Interfaces cannot be defined locally. Why?

Page 31: Nested Classes

Nested Classes 31

Example 6: Local Classes 1 public MaxMin getPair(){

2 class Pair implements MaxMin{

3 private double best;

4 private double worst;

5 public String toString(){

6 return "Best grade: "+best+"\nWorst grade: "+worst+"\n";

7 }

8 public void bestAndWorst(){

9 if(grades.length > 0){

10 best = grades[0];

11 worst = grades[0];

12 for(int i=1; i<grades.length; i++){

13 if (best < grades[i]) best = grades[i];

14 else if (worst > grades[i]) worst = grades[i];

15 }

16 }

17 }

18 }

19 return new Pair();

20 }

Page 32: Nested Classes

Nested Classes 32

Example 6: Local Classes (cont’d)21 public class Course3Test{

22 public static void main(String [] args){

23 Course3 c3 = new Course3(10);

24 Course3.MaxMin cs = c3.getPair();

25 cs.bestAndWorst();

26 System.out.println(cs);

27 }

28 }

Page 33: Nested Classes

Nested Classes 33

Example 6: Local Classes: Transcript

This example is almost the same as Example 2. We will only point out the differences with Example 2.

We first notice that the definition of the class Pair is now moved inside the body of the method getPair(). Notice that this is the only place where the class Pair is used inside the enclosing class.

The second difference is that the class Pair is now without the protected modifier

The third difference is in the main() method of the test class.

Since the class Pair is now locally defined inside a method we cannot refer to it from outside that method.

Instead, we call the method getPair() to return an instance of the Pair class. The remaining part of the code remains the same as in Example 2.

Page 34: Nested Classes

Nested Classes 34

Scope of Local Classes and Local Variables

We have mentioned that local classes are similar to local variablesWe have mentioned earlier that local classes are similar to local variables in many respects

We also recall that a function’s activation record has a short lifetimeThis means that the information in an activation record (local variables, parameters etc) is destroyed immediately the function returns

Now, are objects of local classes also destroyed when the function returns? The question now is what happens to objects of a local class when the enclosing function returns? Do they have the same lifetime as local variables or do they have longer lifetime?

The next example demonstrates two important issues: 1. Objects of local classes can exist much longer after the function returns

The first issue is that objects of local classes can exist much longer after the enclosing function returns

2. Local classes can access only final local variables and function parameters The second issue is to illustrate why local variables/function parameters that a local classes accesses must be declared final

Page 35: Nested Classes

Nested Classes 35

Example 7: Scope of Local Class Objects 1 class LocalVariableAndClassScope{

2 interface Doubler{int twice();} //implicitly static member

3 public static void main(String [] args){

4 Doubler [] allEven = new Doubler[10];

5 for(int i=0; i<allEven.length; i++){

6 final int value = i;

7 class MyDoubler implements Doubler{

8 public int twice(){

9 return 2*value;

10 }

11 }

12 allEven[i] = new MyDoubler();

13 }

14 for(int i=0; i<allEven.length; i++)

15 System.out.println(allEven[i].twice());

16 }

17 }

Page 36: Nested Classes

Nested Classes 36

Example 7: Transcript

The example starts with a definition of an implicitly static member interface, Doubler

The interface has a single integer method twice()

Notice the definition of the local variable value and the local class MyDoubler

Note that these definitions are only visible inside the for-statement block

The statement in on line 12 fills up the MyDoubler array with instances of the local class

The statement in on line 12 fills up the MyDoubler array with different instances of the local class, MyDoubler

Notice that value and MyDoubler are not in scope after line xyAfter the array has been filled up, both the local variable value and the local class MyDoubler are out of scope in the next for-statement

How does twice() access the value local variable and works correctly?But how does the twice() method manage to access the value local variable to work correctly?This is only possible if a copy of that variable has been made before exiting the scope!

Page 37: Nested Classes

Nested Classes 37

Example 7: Transcript

Each instance of a local class makes a private copy of the scope before the scope is exited!

In reality, each instance of a local class has an automatically created private copy of each of the final local variables it uses, so, in effect it has its own private copy of the scope that existed when it was created.The only way to ensure that the values of the variables in the copied scope remain the same is to declare those variables final:

Page 38: Nested Classes

Nested Classes 38

Anonymous Classes

When a local class is used only once, it can be defined anonymously An anonymous class is a local class without a name

That means all what we have said about local classes apply to anonymous classes as well

An anonymous class is defined and instantiated in a single expressionNotice that the definition and instantiation cannot be separated. Why is that?

An anonymous class has no constructors Because the name of a constructor must be the same as the name of the class and the class has no name in this case

Construction parameters can be given through the superclass constructor If parameters are needed to construct an anonymous class, then these parameters can be given through the constructors of the superclass.

When an anonymous class implements an interface, it cannot have any construction parameters. Why? Interfaces cannot be defined anonymously. Why?

Page 39: Nested Classes

Nested Classes 39

Example 8: Anonymous Inner Classes 1 public MaxMin getPair(){

2 return new MaxMin(){

3 private double best;

4 private double worst;

5 public String toString(){

6 return "Best grade: "+best+"\nWorst grade: "+worst+"\n";

7 }

8 public void bestAndWorst(){

9 if(grades.length > 0){

10 best = grades[0];

11 worst = grades[0];

12 for(int i=1; i<grades.length; i++){

13 if (best < grades[i]) best = grades[i];

14 else if (worst > grades[i]) worst = grades[i];

15 }

16 }

17 }

18 };

19 }

Page 40: Nested Classes

Nested Classes 40

Anonymous ClassesExample 8 is almost identical to Example 6. The only thing we need to highlight is the syntax of defining anonymous classes. We present the notes on the next slide

Notice the syntax in this example when an anonymous class implements the interface MaxMin:

new MaxMin(){

// body of anonymous class

};

If the anonymous class is named MyClass, the above (syntax) is equivalent to: class MyClass implements MaxMin{

// body of anonymous class

}

return new MyClass();

If MaxMin were a class instead of an interface, then the keyword implements will be replaced with extends Examples of multiple anonymous classes extending classes will be discussed later

We will consider examples of multiple anonymous inner classes extending (different) implementations within the same class later in our discussion on event-driven programming

Page 41: Nested Classes

Nested Classes 41

Quiz 2(1) Which of the following statements about member classes are correct?

(1) An instance of a member class object is always attached to an instance of the enclosing class

(2) An instance of an enclosing class object is always attached to an instance of its member class

(3) The fully-qualified name of a member class must be used where ever it is used in the enclosing class

(4) Member classes can be overridden just like instance methods can be overridden

(5) A member class is not a subclass of its outer class

(2) Write down the names of two nested classes that can be defined inside a Java code block

(1) One:

(2) Two:

(3) Which of the following statements are correct?

(1) Top-level classes can only have public as an explicit modifier

(2) Member classes are treated as having the public modifier by the JVM

(3) When inner classes were introduced in Java 1.1, the JVM was modified slightly to support them

(4) The JVM treats all nested classes as top-level classes

(5) A nested class belongs to the same package as its enclosing class

(4) Match the following

(1) Member classes, static classes, local class

(2) Cannot be declared public, protected, private or static, cannot be defined inside member classes, can have any access modifier

Page 42: Nested Classes

Nested Classes 42

Review Exercises(1) Consider the following program segment:

class Outer {

private int i;

private boolean b;

class Inner{

private int j;

private float f;

}

}

Give a pictorial representation of the statement

Outer.Inner obj = new Outer().new Inner();

(1) Explain why Java does not allow declaring a static variable or a static local class within a method

(2) Use appropriate examples to explain how nested classes provide addition support for object orientation, code organization and multiple implementation inheritance

(3) Can an interface be defined inside a member class? Give an example or a counter example.

(4) Compare and contrast static member classes and member classes

(5) Write a complete program to illustrate how to access object of an outer class from an object of the inner class

(6) Let B be a member class inside another class A. Let another class C extend B. Is it possible for class C to have a no-arg constructor?

(7) Mention two similarities and two differences between member classes and anonymous classes

Page 43: Nested Classes

Nested Classes 43

References(1) Java in a Nutshell, David Flanagan, O’Reilly Inc., Third Edition, 1999.

(2) Core Java, Cay Horstmann, Chapter 6.

(3) Thinking in Java, Bruce Eckel, 2000.