The JavaTM Tutorial
Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Answers to Questions and Exercises: Nested Classes

Questions

Question 1: The program Problem.java (in a .java source file) doesn't compile. What do you need to do to make it compile? Why?
Answer 1: Add final in front of the declaration of the timer variable. A nested class declared within a method has access to any final, local variables in scope. See ProblemSolved.java (in a .java source file).


Question 2: Use the 5.0 API documentation for the Box (in the API reference documentation) class (in the javax.swing package) to help you answer the following questions.

a. What static nested class does Box define?
Answer 2a: Box.Filler

b. What inner class does Box define?
Answer 2b: Box.AccessibleBox

c. What is the superclass of Box’s inner class?
Answer 2c:[java.awt.]Container.AccessibleAWTContainer

d. Which of Box’s nested classes can you use from any class?
Answer 2d: Box.Filler

e. How do you create an instance of Box’s Filler class?
Answer 2e: new Box.Filler(minDimension, prefDimension, maxDimension)

Exercises

Exercise 1: Get the file Class1.java (in a .java source file).
a. Compile and run Class1. What is the output?
Answer 2a:
InnerClass1: getString invoked.
InnerClass1: getAnotherString invoked.

b. Create a file called Class2.java that defines subclasses of both Class1 and its inner class, InnerClass1. (Call the subclasses Class2 and InnerClass2, respectively.) InnerClass2 should override the getAnotherString method to return "InnerClass2 version of getAnotherString invoked". Class2 should define one constructor and one method:

What is the output when you run Class2?

Answer 2b:
InnerClass1: getString invoked.
InnerClass2 version of getAnother String invoked.

See Class2.java (in a .java source file).


Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.