Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 4 Advanced Class Design

You need to prefix the object reference of the outer class to create an instance of the inner class. In this case, it is a this reference, so you are prefixing it with this before the new operator.

Every inner class is associated with an instance of the outer class. In other words, an inner class is always associated with an enclosing object.

The outer and inner classes share a special relationship, like friends or members of same family. Member accesses are valid irrespective of the access specifiers such as private. However, there is subtle difference. You can access members of an outer class within an inner class without creating an instance; but this is not the case with an outer class. You need to create an instance of inner class in order to access the members (any members, including private members) of the inner class.

One limitation of inner classes is that you cannot declare static members in an inner class, like this:

class Outer {

class Inner {

static int i = 10;

}

}

If you try to do so, you’ll get the following compiler error:

Outer.java:3: inner classes cannot have static declarations static int i = 10;

Points to Remember

Here are some important rules about inner classes and interfaces that might prove useful in the OCPJP 7 exam:

The accessibility (public, protected, etc.) of the inner class is defined by the outer class.

Just like top-level classes, an inner class can extend a class or can implement interfaces. Similarly, an inner class can be extended by other classes, and an inner interface can be implemented or extended by other classes or interfaces.

An inner class can be declared final or abstract.

Inner classes can have inner classes, but you’ll have a hard time reading or understanding such complex nesting of classes. (Meaning: Avoid them!)

Local Inner Classes

A local inner class is defined in a code block (say, in a method, constructor, or initialization block). Unlike static nested classes and inner classes, local inner classes are not members of an outer class; they are just local to the method or code in which they are defined.

99

Chapter 4 Advanced Class Design

Here is an example of the general syntax of a local class:

class SomeClass {

void someFunction() { class Local { }

}

}

As you can see in this code, Local is a class defined within someFunction. It is not available outside of someFunction, not even to the members of the SomeClass. Since you cannot declare a local variable static, you also cannot declare a local class static.

Since you cannot define methods in interfaces, you cannot have local classes or interfaces inside an interface. Nor can you create local interfaces. In other words, you cannot define interfaces inside methods, constructors, and initialization blocks.

Now that you understand the syntax, let’s jump into a practical example. In the FunPaint application, you implemented the Color class as a static nested class. Here is the code you saw in that discussion:

abstract class Shape {

public static class Color {

int m_red, m_green, m_blue; public Color() {

this(0, 0, 0);

}

public Color(int red, int green, int blue) {

m_red = red; m_green = green; m_blue = blue;

}

public String toString() {

return " red = " + m_red + " green = " + m_green + " blue = " + m_blue;

}

// other color members elided

}

// other Shape members elided

}

Now, this toString() method displays a string representation of Color. Assume that you need to display help messages at the bottom of the screen in the FunPaint application. For that you need descriptive messages. Displaying messages in this cryptic format is not very helpful to the reader. So, you want to display the Color string in the following format: "You selected a color with RGB values red = 0 green = 0 blue = 0". For that, you must define a method named getDescriptiveColor() in the class StatusReporter. In getDescriptiveColor(), you must create a derived class of Shape.Color in which the toString method returns this descriptive message. Listing 4-7 is an implementation using local classes.

Listing 4-7.  StatusReporter.java

class StatusReporter {

//important to note that the argument "color" is declared final

//otherwise, the local inner class DescriptiveColor will not be able to use it!! static Shape.Color getDesciptiveColor(final Shape.Color color) {

//local class DescriptiveColor that extends Shape.Color class

class DescriptiveColor extends Shape.Color {

100

Chapter 4 Advanced Class Design

public String toString() {

return "You selected a color with RGB values " + color;

}

}

return new DescriptiveColor();

}

public static void main(String []args) { Shape.Color descriptiveColor =

StatusReporter.getDesciptiveColor(new Shape.Color(0, 0, 0)); System.out.println(descriptiveColor);

}

}

The main method checks if the StatusReporter works fine. This program prints

You selected a color with RGB values red = 0 green = 0 blue = 0  

Let’s see how the local class was defined. The getDescriptiveColor() method takes the plain Shape.Color class object and returns a Shape.Color object. Inside the getDescriptiveColor() method, you have defined the class DescriptiveColor, which is local to this method. This DescriptiveColor is a derived class of Shape.Color. Inside the DescriptiveColor class, the only method defined is the toString() method, which overrides the base class

Shape.Color toString() method. After the definition of the DescriptiveColor class, the getDescriptiveColor class creates an object of the DescriptiveColor class and returns it.

In the Test class, you can see a main() method that just calls the StatusReporter.getDescriptiveColor() method and stores the result in a Shape.Color reference. You will notice that the getDescritiveColor() method returns a DescriptiveColor object, which derives from Shape.Color, so the descriptiveColor variable initialization works fine. In the println, the dynamic type of descriptiveColor is a DescriptiveColor object, and hence the detailed description of the color object is printed.

Did you notice another feature in the getDescriptiveColor() method? Its argument is declared final. What if you remove the final qualifier, as in the following code?

static Shape.Color getDesciptiveColor(Shape.Color color)

Well, you’ll get the following compiler error:

StatusReporter.java:24: local variable color is accessed from within inner class; needs to be declared final

return "You selected a color with RGB values " + color;

^

1 error

Why? One thing you need to remember about local classes is that you can pass only final variables to a local class.

 You can pass only final variables to a local inner class.

101

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]