Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
630
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

8.2 In Fig. 8.25, the association between the ATM and the Screen indicates that:

a.we can navigate from the Screen to the ATM

b.we can navigate from the ATM to the Screen

c.Both a and b; the association is bidirectional

d.None of the above

8.3 Write Java code to begin implementing the design for class Keypad.

Answers to Software Engineering Case Study Self-Review Exercises

8.1 True. The minus sign () indicates private visibility.

8.2 b.

8.3 The design for class Keypad yields the code in Fig. 8.30. Recall that class Keypad has no attributes for the moment, but attributes may become apparent as we continue the implementation. Also note that if we were designing a real ATM, method getInput would need to interact with the ATM's keypad hardware. We will actually do input from the keyboard of a personal computer when we write the complete Java code in Appendix J.

Figure 8.30. Java code for class Keypad based on Fig. 8.24 and Fig. 8.25.

1 // Class Keypad represents an ATM's keypad

2public class Keypad

3{

4

// no attributes have been specified yet

5

 

6// no-argument constructor

7public Keypad()

8{

9} // end no-argument Keypad constructor

11// operations

12public int getInput()

13{

14} // end method getInput

15} // end class Keypad

[Page 406 (continued)]

8.20. Wrap-Up

In this chapter, we presented additional class concepts. The Time class case study presented a complete class declaration consisting of private data, overloaded public constructors for initialization flexibility, set and get methods for manipulating the class's data, and methods that returned String representations of a Time object in two different formats. You also learned that every class can declare a toString method that returns a String representation of an object of the class and that method toString can be called implicitly whenever an object of a class appears in the code where a String is expected.

You learned that the this reference is used implicitly in a class's non-static methods to access the class's instance variables and other non-static methods. You also saw explicit uses of the this reference to access the class's members (including shadowed fields) and how to use keyword this in a constructor to call another constructor of the class.

[Page 407]

The chapter discussed the differences between default constructors provided by the compiler and noargument constructors provided by the programmer. You learned that a class can have references to objects of other classes as membersa concept known as composition. You saw the new enum class type introduced in J2SE 5.0 and learned how it can be used to create a set of constants for use in a program. You learned about Java's garbage collection capability and how it reclaims the memory of objects that are no longer used. The chapter explained the motivation for static fields in a class and demonstrated how to declare and use static fields and methods in your own classes. You also learned how to declare and initialize final variables.

You learned how to package your own classes for reuse and how to import those classes into an application. Finally, you learned that fields declared without an access modifier are given package access by default. You saw the relationship between classes in the same package that allows each class in a package to access the package-access members of other classes in the package.

In the next chapter, you will learn about an important aspect of object-oriented programming in Javainheritance. You will see that all classes in Java are related directly or indirectly to the class called Object. You will also begin to understand how the relationships between classes enable you to build more powerful applications.

[Page 407 (continued)]

Summary

Every class you declare represents a new type in Java.

The public methods of a class are also known as the class's public services or public

interface. The primary purpose of public methods is to present to the class's clients a view of the services the class provides. Clients of the class need not be concerned with how the class accomplishes its tasks. For this reason, private class members are not directly accessible to the class's clients.

An object that contains consistent data has data values that are always kept in range.

A value passed to a method to modify an instance variable is a correct value if that value is in

the instance variable's allowed range. A correct value is always a consistent value, but a consistent value is not correct if a method receives an out-of-range value and sets it to a consistent value to maintain the object in a consistent state.

String class static method format is similar to method System.out.printf except that format returns a formatted String rather than displaying it in a command window.

All objects in Java have a toString method that returns a String representation of the object. Method toString is called implicitly when an object appears in code where a String is needed.

A non-static method of an object implicitly uses keyword this to refer to the object's instance variables and other methods. Keyword this can also be used explicitly.

The compiler produces a separate file with the .class extension for every compiled class.

If a method contains a local variable with the same name as one of its class's fields, the local

variable shadows the field in the method's scope. The method can use the this reference to refer to the shadowed field explicitly.

Overloaded constructors enable objects of a class to be initialized in different ways. The compiler differentiates overloaded constructors by their signatures.

[Page 408]

Every class must have at least one constructor. If none are provided, the compiler creates a

default constructor that initializes the instance variables to the initial values specified in their declarations or to their default values.

If a class declares constructors, the compiler will not create a default constructor. To specify the

default initialization for objects of a class with multiple constructors, the programmer must declare a no-argument constructor.

Set methods are commonly called mutator methods because they typically change a value. Get

methods are commonly called accessor methods or query methods. A predicate method tests whether a condition is true or false.

A class can have references to objects of other classes as members. Such a capability is called composition and is sometimes referred to as a has-a relationship.

All enum types are reference types. An enum type is declared with an enum declaration, which is a

comma-separated list of enum constants. The declaration may optionally include other components of traditional classes, such as constructors, fields and methods.

enum types are implicitly final, because they declare constants that should not be modified.

enum constants are implicitly static.

Any attempt to create an object of an enum type with operator new results in a compilation error.

enum constants can be used anywhere constants can be used, such as in the case labels of switch statements and to control enhanced for statements.

Each enum constant in an enum declaration is optionally followed by arguments which are passed to the enum constructor.

For every enum, the compiler generates a static method called values that returns an array of the enum's constants in the order in which they were declared.

EnumSet static method range takes two parametersthe first enum constant in a range and the

last enum constant in a rangeand returns an that EnumSet contain all the constants between these two constants, inclusive.

Every class in Java has the methods of class Object, one of which is the finalize method.

The Java Virtual Machine (JVM) performs automatic garbage collection to reclaim the memory

occupied by objects that are no longer in use. When there are no more references to an object, the object is marked for garbage collection by the JVM. The memory for such an object can be reclaimed when the JVM executes its garbage collector.

The finalize method is called by the garbage collector just before it reclaims the object's memory. Method finalize does not take parameters and has return type void.

The garbage collector may never execute before a program terminates. Thus, it is unclear if, or when, method finalize will be called.

A static variable represents classwide information that is shared among all objects of the class.

Static variables have class scope. A class's public static members can be accessed through a

reference to any object of the class, or they can be accessed by qualifying the member name with the class name and a dot (.). A class's private static class members can be accessed only through methods of the class.

static class members exist even when no objects of the class existthey are available as soon as

the class is loaded into memory at execution time. To access a private static member when no objects of the class exist, a public static method must be provided.

System class static method gc indicates that the garbage collector should make a best-effort attempt to reclaim objects that are eligible for garbage collection.

[Page 409]

A method declared static cannot access non-static class members, because a static method can be called even when no objects of the class have been instantiated.

The this reference cannot be used in a static method.

A static import declaration enables programmers to refer to imported static members without

the class name and a dot (.). A single static import declaration imports one static member, and a static import on demand imports all static members of a class.

In the context of an application, the principle of least privilege states that code should be

granted only the amount of privilege and access that the code needs to accomplish its designated task.

Keyword final specifies that a variable is not modifiablein other words, it is constant. Constants

can be initialized when they are declared or by each of a class's constructors. If a final variable is not initialized, a compilation error occurs.

Software is constructed from existing, well-defined, carefully tested, well-documented, portable,

widely available components. Software reusability speeds the development of powerful, highquality software. Rapid application development (RAD) is of great interest today.

Java programmers now have thousands of classes in the Java API from which to choose to help

them implement Java programs. The Java API classes enable Java programmers to bring new applications to market faster by using preexisting, tested components.

The client of a class cares about the functionality the class offers, but not about how the

functionality is implemented. This is referred to as data abstraction. Although programmers may know the details of a class's implementation, they should not write code that depends on these details. This enables a class to be replaced with another version without affecting the rest of the system.

An abstract data type (ADT) consists of a data representation and the operations that can be performed on that data.

Each class in the Java API belongs to a package that contains a group of related classes. Packages help manage the complexity of application components and facilitate software reuse.

Packages provide a convention for unique class names that helps prevent class name conflicts.

Before a class can be imported into multiple applications, the class must be placed in a package.

There can be only one package declaration in each Java source-code file, and it must precede all other declarations and statements in the file.

Every package name should start with your Internet domain name in reverse order. After the domain name is reversed, you can choose any other names you want for your package.

When compiling a class in a package, the javac command-line option -d specifies where to store the package and causes the compiler to create the package's directories if they do not exist.

The package name is part of the fully qualified class name. This helps prevent name conflicts.

A single-type-import declaration specifies one class to import. A type-import-on-demand declaration imports only the classes that the program uses from a particular package.

The compiler uses a class loader to locate the classes it needs in the classpath. The classpath consists of a list of directories or archive files, each separated by a directory separator.

The classpath for the compiler and JVM can be specified by providing the -classpath option to

the javac or java command, or by setting the CLASSPATH environment variable. The classpath for the JVM can also be specified via the -cp command-line option. If classes must be loaded from the current directory, include a dot (.) in the classpath.

If no access modifier is specified for a method or variable when it is declared in a class, the method or variable is considered to have package access.

[Page 410]

Terminology

abstract data type (ADT) access modifier

accessor method attribute behavior

class library class loader class scope class variable classpath

-classpath command line argument to javac CLASSPATH environment variable

composition constant variable

-d command line argument to javac

data abstraction default constructor directory separator enum keyword enum constant

EnumSet class extensible language extensions mechanism finalize method

format method of String garbage collector

gc method of System has-a relationship

mark an object for garbage collection memory leak

mutator method name collision name conflict

no-argument constructor optional package overloaded constructors package access

package declaration predicate method principle of least privilege private access modifier protected access modifier public access modifier query method

range method of EnumSet

rapid application development (RAD) resource leak

service of a class

simple name of a class, field or method single static import

single-type-import declaration static field (class variable) static import

static import on demand termination housekeeping

this keyword

type-import-on-demand declaration

validity checking

values method of an enum

variable is not modifiable

[Page 410 (continued)]

Self-Review Exercises

8.1 Fill in the blanks in each of the following statements:

a.When compiling a class in a package, the javac command-line option

__________specifies where to store the package and causes the compiler to create the package's directories if they do not exist.

b.String class static method __________ is similar to method System.out.printf, but returns a formatted String rather than displaying a String in a command window.

c.If a method contains a local variable with the same name as one of its class's fields, the local variable __________ the field in that method's scope.

d.The __________ method is called by the garbage collector just before it reclaims an object's memory.

e.A(n) __________ declaration specifies one class to import.

f.If a class declares constructors, the compiler will not create a(n) __________

.

g.An object's __________ method is called implicitly when an object appears in code where a String is needed.

h.Get methods are commonly called__________ or__________ .

i.A(n) __________ method tests whether a condition is true or false.

[Page 411]

j. For every enum, the compiler generates a static method called __________

that returns an array of the enum's constants in the order in which they were declared.

k.Composition is sometimes referred to as a(n) __________ relationship.

l.A(n) __________ declaration contains a comma-separated list of constants.

m.A(n) __________ variable represents classwide information that is shared by all the objects of the class.

n.A(n) __________ declaration imports one static member.

o.The __________ states that code should be granted only the amount of privilege and access that the code needs to accomplish its designated task.

p.Keyword __________ specifies that a variable is not modifiable.

q.A(n) __________ consists of a data representation and the operations that can be performed on the data.

r.There can be only one __________ in a Java source-code file, and it must precede all other declarations and statements in the file.

s.A(n) __________ declaration imports only the classes that the program uses from a particular package.

t.The compiler uses a(n) __________ to locate the classes it needs in the classpath.

u.The classpath for the compiler and JVM can be specified with the __________

option to the javac or java command, or by setting __________ the environment variable.

v.Set methods are commonly called __________ because they typically change a value.

w.A(n) __________ imports all static members of a class.

x.The public methods of a class are also known as the class's __________ or

__________ .

y.System class static method __________ indicates that the garbage collector should make a best-effort attempt to reclaim objects that are eligible for garbage collection.

z.An object that contains __________ has data values that are always kept in range.