Learning Outcome - PowerPoint PPT Presentation

About This Presentation
Title:

Learning Outcome

Description:

Title: ICS 201: Introduction To Computer Science Subject: Part II Slides Author: Lahouari Ghouti Last modified by: ccse-gen Created Date: 1/15/1997 12:24:36 PM – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 44
Provided by: Lahouar1
Category:
Tags: learning | outcome

less

Transcript and Presenter's Notes

Title: Learning Outcome


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

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

3
Introduction to Nested Classes (contd)
  • 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
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
5
Nested Classes at a Glance Transcript
  • A static member class defined with the static
    keyword
  • An interface is always a static member
  • A member class inside another class. Note that it
    is not static
  • A local class defined inside the method
    myMethod()
  • A method that returns an object of a class that
    implements StaticMemberInterface
  • The 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 classs definition

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.

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

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
    class
  • A 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 class
  • A static member class has access to all static
    members of its outer class, including private
    static members
  • static 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

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 array
  • The class that implements the MaxMin interface
    must have access to the grades array
  • With 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 value
  • This 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 grades
  • With this class, a single method is required to
    return an instance of Pair that using a single
    traversal of the grades array

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 gt
0) 13 best grades0 14
worst grades0 15 for(int i1
iltgrades.length i) 16 if (best
lt gradesi) best gradesi 17
else if (worst gt gradesi) worst gradesi 18
19 20 21
11
Example 1 static Member Classes (contd)
22 Course1(int size) 23 grades new
doublesize 24 for(int i0 iltsize
i) 25 gradesi 100Math.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
12
static Member Classes Transcript
  • This is the grades array we introduced earlier
  • Also this is the MaxMin interface we already
    introduced
  • This is the Pair class implementing the MaxMin
    interface
  • The class pair has two private fields to hold the
    best and worst grades
  • The Pair class overrides the inherited toString()
    method
  • The bestAndWorst() method determines the best and
    worst grades and store them in the two instance
    variables of the Pair class
  • It is assumed that the first element in the array
    is the best and the worst at the same time
  • These values are updated as he remaining elements
    in the array are inspected
  • A constructor of the COurse1 class that
    initializes the grades array with ten random
    values
  • Each value is a number between 0 and 100
  • getPair() method is an instance method of the
    Couse1 class that returns an instance of the Pair
    class

13
static Member Classes Transcript
  • Class Course1Test is the driver class used to
    test the Course1 class
  • The statement at line xy creates an object of
    type Pair
  • Observe this object-creation expression
    carefully. In particular the name of the class
    Pair is prefixed with the name of its outer
    class, Course1
  • This 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 package
  • The instance of the Pair class is now used to
    compute the best and worst grades
  • Finally the program prints the values of the best
    and worst grades found
  • MCQ
  • What is the significance of the line Course1 c1
    new Course1(10)
  • not needed
  • necessary to initialize the array

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.class
  • MaxMin.class
  • Course1.Pair.class
  • Course1Test.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 Pair
  • A static member class accessing the private
    static member of its outer class
  • A static member class implementing an interface

15
Quiz 1
  1. Select all correct answers in the following.
    Top-level classes and interfaces
  2. Are always in the same package
  3. Are always defined at top-level
  4. Where not available before Jva 1.1
  5. Do not use access modifiers
  6. Which of the following statements about nested
    classes are correct?
  7. Static member classes can access all other
    members of the outer class
  8. A static member class must be defined as the
    first member of its enclosing class
  9. All non-static classes are called inner classes
  10. An outer class of a static member class must also
    be static
  11. Using the MaxMin interface in Example 1, the
    statement MaxMin pairs new MaxMin10
  12. Is invalid because MaxMin is an interface
  13. Is valid and creates ten objects
  14. Is valid and creates eleven objects
  15. Is valid and creates only one object

16
Member Classes
  • A member class is defined as a non-static member
    of another class
  • A 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 while
  • Every member object is associated with an object
    of its enclosing class

17
Member Classes (contd)
  • 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 class
  • Note 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

18
Example 2 Member Classes
1 protected class Pair implements MaxMin 2
public void bestAndWorst() 3
if(grades.length gt 0) 4 best
grades0 5 worst grades0 6
for(int i1 iltgrades.length i) 7
if (best lt gradesi) best
gradesi 8 else if (worst gt
gradesi) worst gradesi 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
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

20
Example 2 Transcript (contd)
  • 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),
    while
  • An object of member class requires an object of
    its enclosing class to be created (Course2Test)

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 Pair
  • The constructor of class Course2 simply displays
    a message and then creates an object of class
    Pair
  • The constructor of class Pair consists of a
    simple print statement
  • The 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 subclass
  • This 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

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 OverridingMemberClas
s() 13 System.out.println("OverridingMember
Class 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
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 objects
  • Note 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
    done
  • This is done simply as indicated
  • To refer to the outer class object, use the
    notation OuterClass.this
  • when 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.

24
Example 4 Keyword this in Member Classes
// code omitted 1 public void bestAndWorst()
2 if(Course2.this.grades.length gt 0) 3
this.best Course2.this.grades0 4
this.worst Course2.this.grades0
5 for(int i1 iltgrades.length i)
6 if (best lt gradesi) best
gradesi 7 else if (worst gt
gradesi) worst gradesi 8 9
10 // code omitted
25
Example 5 Extending Member Classes
  • Example 3 shows that member classes are
    inherited but cannot be overridden
  • In 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

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("Extending
MemberClass 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
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

28
Example 5 Transcript (contd)
  • 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

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 visibility
  • With 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 file
  • This allows any conforming Java compiler to
    enforce the access modifiers and prevent member
    classes from being accessed in unintended ways

30
Local Classes
  • When a class name is used once it can be defined
    locally
  • When 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
    code
  • A 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 block
  • Furthermore, 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?

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 gt 0) 10 best
grades0 11 worst grades0 12
for(int i1 iltgrades.length
i) 13 if (best lt gradesi)
best gradesi 14 else if
(worst gt gradesi) worst gradesi 15
16 17 18
19 return new Pair() 20
32
Example 6 Local Classes (contd)
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
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.

34
Scope of Local Classes and Local Variables
  • We have mentioned that local classes are similar
    to local variables
  • We have mentioned earlier that local classes are
    similar to local variables in many respects
  • We also recall that a functions activation
    record has a short lifetime
  • This 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

35
Example 7 Scope of Local Class Objects
1 class LocalVariableAndClassScope 2
interface Doublerint twice() //implicitly
static member 3 public static void
main(String args) 4 Doubler allEven
new Doubler10 5 for(int i0
iltallEven.length i) 6 final int
value i 7 class MyDoubler implements
Doubler 8 public int twice() 9
return 2value 10 11
12 allEveni new MyDoubler() 13
14 for(int i0 iltallEven.length
i) 15 System.out.println(allEveni.twic
e()) 16 17
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 xy
  • After 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!

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

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 expression
  • Notice 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?

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 gt 0) 10 best
grades0 11 worst
grades0 12 for(int i1
iltgrades.length i) 13 if
(best lt gradesi) best gradesi 14
else if (worst gt gradesi) worst
gradesi 15 16
17 18 19
40
Anonymous Classes
  • Example 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

41
Quiz 2
  1. Which of the following statements about member
    classes are correct?
  2. An instance of a member class object is always
    attached to an instance of the enclosing class
  3. An instance of an enclosing class object is
    always attached to an instance of its member
    class
  4. The fully-qualified name of a member class must
    be used where ever it is used in the enclosing
    class
  5. Member classes can be overridden just like
    instance methods can be overridden
  6. A member class is not a subclass of its outer
    class
  7. Write down the names of two nested classes that
    can be defined inside a Java code block
  8. One
  9. Two
  10. Which of the following statements are correct?
  11. Top-level classes can only have public as an
    explicit modifier
  12. Member classes are treated as having the public
    modifier by the JVM
  13. When inner classes were introduced in Java 1.1,
    the JVM was modified slightly to support them
  14. The JVM treats all nested classes as top-level
    classes
  15. A nested class belongs to the same package as its
    enclosing class
  16. Match the following
  17. Member classes, static classes, local class
  18. Cannot be declared public, protected, private or
    static, cannot be defined inside member classes,
    can have any access modifier

42
Review Exercises
  • 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()
  • Explain why Java does not allow declaring a
    static variable or a static local class within a
    method
  • Use appropriate examples to explain how nested
    classes provide addition support for object
    orientation, code organization and multiple
    implementation inheritance
  • Can an interface be defined inside a member
    class? Give an example or a counter example.
  • Compare and contrast static member classes and
    member classes
  • Write a complete program to illustrate how to
    access object of an outer class from an object of
    the inner class
  • 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?
  • Mention two similarities and two differences
    between member classes and anonymous classes

43
References
  1. Java in a Nutshell, David Flanagan, OReilly
    Inc., Third Edition, 1999.
  2. Core Java, Cay Horstmann, Chapter 6.
  3. Thinking in Java, Bruce Eckel, 2000.
Write a Comment
User Comments (0)
About PowerShow.com