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

Chapter 4 Advanced Class Design

public String toString() {

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

}

};

}

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

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

}

}

It prints

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

That’s nice. The rest of the program, including the main() method, remains the same and the getDescriptiveColor() method became simpler! You did not explicitly create a class with a name (which was DescriptiveColor); instead you just created a derived class of Shape.Color “on the fly” in the return statement. Note that the keyword class is also not needed.

Points to Remember

These points about anonymous classes concern questions that might be asked on the OPCJP 7 exam:

Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class.

You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.

Enum Data Types

There are many situations where you want to restrict the user to providing input from a predefined list. For instance, you might want the user to choose from a set of constants defining several printer types:

public static final int DOTMATRIX = 1; public static final int INKJET = 2; public static final int LASER = 3;

The solution works. In this case, however, you could pass any other integer (say 10), and compiler would happily take it. Therefore, this solution is not a typesafe solution.

To avoid this condition, you may define you own class (say PrinterType) and allow only legitimate values. However, you need to define the class and its attributes manually. That’s where formerly you could have employed Joshua Bloch’s typesafe enumeration patterns. But don’t worry—you don’t need to learn those patterns anymore. Java 5 introduced the data type enum to help you in such situations.

Listing 4-9 defines an enum class (yes, enums are special classes) for the above example.

103

Chapter 4 Advanced Class Design

Listing 4-9.  EnumTest.java

//define an enum for classifying printer types enum PrinterType {

DOTMATRIX, INKJET, LASER

}

//test the enum now

public class EnumTest { PrinterType printerType;

public EnumTest(PrinterType pType) { printerType = pType;

}

public void feature() {

// switch based on the printer type passed in the constructor switch(printerType){

case DOTMATRIX:

System.out.println("Dot-matrix printers are economical and almost obsolete"); break;

case INKJET:

System.out.println("Inkjet printers provide decent quality prints"); break;

case LASER:

System.out.println("Laser printers provide best quality prints"); break;

}

}

public static void main(String[] args) {

EnumTest enumTest = new EnumTest(PrinterType.LASER); enumTest.feature();

}

}

It prints

Laser printers provide best quality prints

Let’s probe the Listing 4-9 example in more detail.

In a switch-case statement, you do not need to provide the fully qualified name for enum elements. This is because switch takes an instance of the enum type, and hence switch-case understands the context (type) in which you are specifying enum elements.

You cannot provide any input while creating an instance of enumTest other than that specified in the enum definition. That makes enum typesafe.

Note that you can declare an enum (PrinterType in this case) in a separate file, just like you can declare any other normal Java class.

104

Chapter 4 Advanced Class Design

Now that you understand the basic concept of enum data type, let’s look at a more detailed example in which you define member attributes and methods in an enum data type. Yes, you can define methods or fields in an enum definition, as shown in Listing 4-10.

Listing 4-10.  PrinterType.java

public enum PrinterType {

DOTMATRIX(5), INKJET(10), LASER(50);

private int pagePrintCapacity;

private PrinterType(int pagePrintCapacity) { this.pagePrintCapacity = pagePrintCapacity;

}

public int getPrintPageCapacity() { return pagePrintCapacity;

}

}

// EnumTest.java public class EnumTest {

PrinterType printerType;

public EnumTest(PrinterType pType) { printerType = pType;

}

public void feature() { switch (printerType) { case DOTMATRIX:

System.out.println("Dot-matrix printers are economical"); break;

case INKJET:

System.out.println("Inkjet printers provide decent quality prints"); break;

case LASER:

System.out.println("Laser printers provide the best quality prints"); break;

}

System.out.println("Print page capacity per minute: " + printerType.getPrintPageCapacity());

}

public static void main(String[] args) {

EnumTest enumTest1 = new EnumTest(PrinterType.LASER); enumTest1.feature();

EnumTest enumTest2 = new EnumTest(PrinterType.INKJET); enumTest2.feature();

}

}

105

Chapter 4 Advanced Class Design

The output of the above program is given below:

Laser printers provide the best quality prints Print page capacity per minute: 50

Inkjet printers provide decent quality prints Print page capacity per minute: 10

Well, what do you observe in this new version of enum example program? You defined a new attribute, a new constructor, and a new method for the enum class. The attribute pagePrintCapacity is set by the initial values specified with enum elements (such as LASER(50)), which calls the constructor of the enum class. However, the enum class cannot have a public constructor, or the compiler will complain with following message: "Illegal modifier for the enum constructor; only private is permitted."

A constructor in an enum class can only be specified as private.

Points to Remember

Enums are implicitly declared public, static, and final, which means you cannot extend them.

When you define an enumeration, it implicitly inherits from java.lang.Enum. Internally, enumerations are converted to classes. Further, enumeration constants are instances of the enumeration class for which the constant is declared as a member.

You can apply the valueOf() and name() methods to the enum element to return the name of the enum element.

If you declare an enum within a class, then it is by default static.

You cannot use the new operator on enum data types, even inside the enum class.

You can compare two enumerations for equality using == operator.

When an enumeration constant’s toString() method is invoked, it prints the name of the enumeration constant.

The static values() method in the Enum class returns an array of the enumeration constants when called on an enumeration type.

Enumeration constants cannot be cloned. An attempt to do so will result in a

CloneNotSupportedException.

If enumeration constants are from two different enumerations, the equals() method does not return true.

Enum avoids magic numbers, which improves readability and understandability of the source code. Also, enums are typesafe constructs. Therefore, you should use enums wherever applicable.

106

Chapter 4 Advanced Class Design

Question time!

1.Which of the following statements is true?

A.You cannot extend a concrete class and declare that derived class abstract.

B.You cannot extend an abstract class from another abstract class.

C.An abstract class must declare at least one abstract method in it.

D.You can create instantiate of a concrete subclass of an abstract class but cannot create instance of an abstract class itself.

Answer: D. You can create instantiate of a concrete subclass of an abstract class but cannot create instance of an abstract class itself.

2.Choose the best answer based on the following class definition: public abstract final class Shape { } 

A.Compiler error: a class must not be empty.

B.Compiler error: illegal combination of modifiers abstract and final.

C.Compiler error: an abstract class must declare at least one abstract method.

D.No compiler error: this class definition is fine and will compile successfully. Answer: B. Compiler error: illegal combination of modifiers abstract and final.

(You cannot declare an abstract class final since an abstract class must to be extended. Class can be empty in Java, including abstract classes. An abstract class can declare zero or more abstract methods.)

3.Look at the following code and choose the right option for the word <access-modifier>:

//Shape.java public class Shape {

protected void display() { System.out.println("Display-base");

}

}

//Circle.java

public class Circle extends Shape { <access-modifier> void display(){

System.out.println("Display-derived");

}

} 

107

Chapter 4 advanCed Class design

a.Only protected can be used.

B.public and protected both can be used.

C.public, protected, and private can be used.

d.Only public can be used.

Answer: B. public and protected both can be used.

(You can provide only a less restrictive or same-access modifier when overriding a method.)

4.Consider this program to answer the following question:

class Shape {

public Shape() {

System.out.println("Shape constructor");

}

public class Color {

public Color() {

System.out.println("Color constructor");

}

}

}

class TestColor {

public static void main(String []args) {

Shape.Color black = new Shape().Color(); // #1

}

}

What will be the output of the program?

a.Compile error: the method Color() is undefined for the type shape.

B.Compile error: invalid inner class.

C.Works fine: shape constructor, Color constructor.

d.Works fine: Color constructor, shape constructor.

Answer: a. Compile error: the method Color() is undefined for the type shape.

(You need to create an instance of outer class shape in order to create an inner class instance).

5.if you replace the Color class instantiation statement (tagged as #1 inside a comment in the program given in the previous questions) with the following statement, what would be the output of the program?

Shape.Color black = new Shape().new Color();

a.Works fine and will print this output:

shape constructor Color constructor

108

Chapter 4 Advanced Class Design

B.Works fine and will print this output:

Color constructor Shape constructor

C.Compiler error: The method Color() is undefined for the type Shape.

D.Compile without error but results in a runtime exception.

Answer: A. Works fine and will print this output:

Shape constructor

Color constructor

6.What will be the output of the given program?

class Shape {

private boolean isDisplayed; protected int canvasID; public Shape() {

isDisplayed = false; canvasID = 0;

}

public class Color {

public void display() {

System.out.println("isDisplayed: "+isDisplayed); System.out.println("canvasID: "+canvasID);

}

}

}

class TestColor {

public static void main(String []args) { Shape.Color black = new Shape().new Color(); black.display();

}

}

A.Compiler error: an inner class can only access public members of the outer class.

B.Compiler error: an inner class cannot access private members of the outer class.

C.Runs and prints this output:

isDisplayed: false canvasID: 0

D.Compiles fine but crashes with a runtime exception.

Answer: C. Runs and prints this output:

isDisplayed: false canvasID: 0

(An inner class can access all members of an outer class, including the private members of the outer class).

109

Chapter 4 Advanced Class Design

7.Look at this program and predict the output:

public class EnumTest { PrinterType printerType;

enum PrinterType {INKJET, DOTMATRIX, LASER}; public EnumTest(PrinterType pType) {

printerType = pType;

}

public static void main(String[] args) { PrinterType pType = new PrinterType();

EnumTest enumTest = new EnumTest(PrinterType.LASER);

}

}

A.Prints the output printerType:LASER.

B.Compiler Error: enums must be declared static.

C.Compiler Error: cannot instantiate the type EnumTest.PrinterType.

D.This program will compile fine, and when run, will crash and throw a runtime exception. Answer: C. Compiler Error: cannot instantiate the type EnumTest.PrinterType.

(You cannot instantiate an enum type using new.)

8.Is the enum definition given below correct?

public enum PrinterType {

 

 

private int pagePrintCapacity;

//

#1

DOTMATRIX(5), INKJET(10), LASER(50);

//

#2

 

 

private PrinterType(int pagePrintCapacity) { this.pagePrintCapacity = pagePrintCapacity;

}

public int getPrintPageCapacity() { return pagePrintCapacity;

}

}

A.Yes, this enum definition is correct and will compile cleanly without any warnings or errors.

B.No, this enum definition is incorrect and will result in compile error(s).

C.No, this enum definition will result in runtime exception(s).

D.Yes, this enum definition is correct but will compile with warnings.

110

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