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

Chapter 4 Advanced Class Design

Static Nested Classes (or Interfaces)

You can define a class (or interface) as a static member inside another class (or interface). Since the outer type can be a class or an interface and the inner ones can also be a class or interface, there are four combinations. The following are examples of these four types so that you can see their syntax:

class Outer { // an outer class has a static nested class static class Inner {}

}

interface Outer { // an outer interface has a static nested class static class Inner {}

}

class Outer { // an outer class has a static nested interface static interface Inner {}

}

interface Outer { // an outer interface has a static nested interface static interface Inner {}

}

You don’t have to explicitly use the static keyword with a nested interface, since it is implicitly static. Now, let’s look at an example that creates as well as uses static nested classes.

Recall the FunPaint example in Chapter 3 that implements a Color class with fields of m_red, m_green, and m_blue. Since all shapes can be colored, you can define the Color class within the Shape class, as shown in Listing 4-5.

Listing 4-5.  TestColor.java

abstract class Shape {

public static class Color {

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

// call the other overloaded Color constructor by passing default values 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

}

public class TestColor {

public static void main(String []args) {

//since Color is a static nested class,

//we access it using the name of the outer class, as in Shape.Color

//note that we do not (and cannot) instantiate Shape class for using Color class

96

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