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

Chapter 3 Java Class Design

In essence, here are the advantages of using packages:

Packages reduce complexity by facilitating categorization of similar classes.

Packages provide namespace management. For example, two developers can define the same type name without ending up in a name clash by putting the name in different packages.

Packages offer access protection (recall the discussion of the default access modifier).

The Java SDK is categorized in various packages. For example, java.lang provides basic language functionality and fundamental types, and java.io can be used to carry out file-related operations.

How can you create your own packages and use (or import) classes from them in other packages? We’ll discuss that next.

Working with Packages

When you want to include a class in a package, you just need to declare it in the class using the package statement. In the FunPaint application, you have the class Circle. If you want to include this class in package graphicshape, then the following declaration would work:

// Circle.java package graphicshape;

public class Circle { //class definition

}

Now, let's say that you want to use this Circle class in your Canvas class (which is in a different package); see Listing 3-20.

Listing 3-20.  Canvas.java

//Canvas.java package appcanvas;

public class Canvas {

public static void main(String[] args) { Circle circle = new Circle(); circle.area();

}

}

This code results in the following error message from the compiler: "Circle cannot be resolved to a type". Well, you can remove this error by providing the fully qualified class name, as shown:

//Canvas.java

package appcanvas;

public class Canvas {

public static void main(String[] args) {

graphicshape.Circle circle = new graphicshape.Circle(); circle.area();

}

}

78

Chapter 3 Java Class Design

Another and more convenient way to resolve the error is to use the import statement. The import statement directs the compiler where to search for the definition of the used type. In this example, you will import from the

graphicshape package:

// Canvas.java package appcanvas;

import graphicshape.Circle;

public class Canvas {

public static void main(String[] args) { Circle circle = new Circle(); circle.area();

}

}

You need to remember that package statement should appear first, followed by import statement(s). Obviously, you can have only one package statement in a java source file.

Let’s assume that you wanted to use various shapes like Circle, Square, Triangle, etc. (belonging to graphicshape package) in the Canvas implementation. You can use one import statement for each graphicshape class (such as import graphicshape.Circle; and import graphicshape.Square;). In such cases, a more convenient way to use the import statement is to use import with a wildcard symbol “*”, which means “include all

classes in that package,” as shown:

import graphicshape.*;

Note that physical hierarchy (the direct structure in your file system) should reflect the package hierarchy.

You do not need to import java.lang to use the basic functionality of the language. This is the only package­ that is implicitly imported, and the classes in this package are available for use in all programs.

Static Import

Recollect the implementation of the area() method in Listing 3-13, which is reproduced here:

public double area() {

return Math.PI * radius * radius;

}

The implementation uses a static member PI of the Math package; that’s why we used PI with package reference. Java 5 introduced a new feature—static import—that can be used to import the static members of the imported package or class. You can use the static members of the imported package or class as if you have defined the static member in the current class. To avail yourself of the feature, you must use “static” in the import declaration. Let’s

reimplement the area() method with a static import:

import static java.lang.Math.PI;

// class declaration and other members public double area() {

return PI * radius * radius;

}

 

79

 

Chapter 3 Java Class Design

You can also use wildcard character “*” to import all static members of a specified package of class.

Always remember that static import only imports static members of the specified package or class.

A word of caution: Although it is quite convenient to use static imports, it may introduce confusion for any developer who is reading later, especially if the current class also defines similar members. It might become difficult to distinguish between a statically imported definition and a locally specified definition.

Naming Conventions for Java Packages 

Oracle recommends the following naming conventions for Java packages:

A hierarchical structure is used normally to define packages and subpackages.

All Java packages usually use lowercase letters.

A product may use an organization structure to define a package hierarchy. For instance, a company (say COMP) has many products, one of which is PROD; one of the features in this product is FTUR; and one of the packages in this feature is PCKG. In this case, the package hierarchy would be comp.prod.ftur.pckg.

A reversed internet domain name may also serve the purpose of a package hierarchy, such as com.company.feature.

If the product name or company name has a hyphen or any other special character, employ the underscore symbol in place of the hyphen and other special character.

Question Time! 

In the FunPaint application, you can color objects. You need the class Color to implement this functionality. This class should use RGB (red, green, blue) color scheme. These three color component values should be stored as int values in three fields. The class should implement a default constructor setting the color values to zero and another constructor that takes these three component values as arguments.

1.What will be the output of this program?

class Color {

int red, green, blue;

void Color() { red = 10;

green = 10; blue = 10;

}

80

Chapter 3 Java Class Design

void printColor() {

System.out.println("red: " + red + " green: " + green + " blue: " + blue);

}

public static void main(String [] args) { Color color = new Color(); color.printColor();

}

}

A.Compiler error: no constructor provided for the class.

B.Compiles without errors, and when run, it prints the following: red: 0 green: 0 blue: 0.

C.Compiles without errors, and when run, it prints the following: red: 10 green: 10 blue: 10.

D.Compiles without errors, and when run, crashes by throwing NullPointerException.

Answer: B. Compiles without errors, and when run, it prints the following: red: 0 green: 0 blue: 0.

(Remember that a constructor does not have a return type; if a return type is provided, it is treated as a method in that class. In this case, since Color had void return type, it became a method named Color() in the Color class, with the default Color constructor provided by the compiler. By default, data values are initialized to zero, hence the output.)

2.Look at the following code and predict the output:

class Color {

int red, green, blue;

Color() {

Color(10, 10, 10);

}

Color(int r, int g, int b) { red = r;

green = g; blue = b;

}

void printColor() {

System.out.println("red: " + red + " green: " + green + " blue: " +

blue);

}

public static void main(String [] args) { Color color = new Color(); color.printColor();

}

}

81

Chapter 3 Java Class Design

A.Compiler error: cannot find symbol.

B.Compiles without errors, and when run, it prints the following: red: 0 green: 0 blue: 0.

C.Compiles without errors, and when run, it prints the following: red: 10 green: 10 blue: 10.

D.Compiles without errors, and when run, crashes by throwing NullPointerException.

Answer: A. Compiler error: cannot find symbol.

(The compiler looks for the method Color() when it reaches this statement: Color(10, 10, 10);. The right way to call another constructor is to use the this keyword as follows: this(10, 10, 10);).

3.In the FunPaint application, you need to code classes to draw rectangles. A rectangle can have plain or rounded edges. You also need to color a (plain or rounded) rectangle. How will you define classes for creating these plain, colored, and rounded rectangles? You can use is-a relationships as needed.

Look at the following option to implement the required functionality:

class Rectangle { /* */ }

class ColoredRectangle extends Rectangle { /* */ } class RoundedRectangle extends Rectangle { /* */ }

class ColoredRoundedRectangle extends ColoredRectangle, RoundedRectangle { /* */ }

Choose an appropriate option:

A.Compiler error: ‘{‘ expected cannot extend two classes.

B.Compiles without errors, and when run, crashes with the exception

MultipleClassInheritanceException.

C.Compiles without errors, and when run, crashes with the exception

NullPointerException.

D.Compiles without errors, and when run, crashes with the exception

MultipleInheritanceError.

Answer: A. Compiler error: ‘{‘ expected – cannot extend two classes.

(This program will result in a compilation error since Java does not support multiple inheritance.)

4.In the FunPaint application, you can fill colors to various shape objects. To implement it, you need to implement a Color class. The Color class has three members, m_red, m_green, and m_blue. Focus on the toString() method and check if it works fine.

Choose the best option based on the following program:

class Color {

int red, green, blue;

Color() {

this(10, 10, 10);

}

82

Chapter 3 Java Class Design

Color(int r, int g, int b) { red = r;

green = g; blue = b;

}

public String toString() {

return "The color is: " + red + green + blue;

}

public static void main(String [] args) { // implicitly invoke toString method System.out.println(new Color());

}

}

A.Compiler error: incompatible types.

B.Compiles without errors, and when run, it prints the following: The color is: 30.

C.Compiles without errors, and when run, it prints the following: The color is: 101010.

D.Compiles without errors, and when run, it prints the following: The color is: red green blue.

Answer: C. Compiles without errors, and when run, it prints the following: The color is: 101010.

(The toString() implementation has the expression “The color is: “ + red + blue + green. Since the first entry is String, the + operation becomes the string concatenation operator with resulting string “The color is: 10”. Following that, again there is a concatenation operator + and so on until finally it prints “The color is: 101010”).

5.Choose the best option based on the following program:

class Color {

int red, green, blue;

Color() {

this(10, 10, 10);

}

Color(int r, int g, int b) { red = r;

green = g; blue = b;

}

String toString() {

return "The color is: " + " red = " + red + " green = " + green + " blue = " + blue;

}

public static void main(String [] args) { // implicitly invoke toString method System.out.println(new Color());

}

}

83

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