MyException - 我的异常网
当前位置:我的异常网» 编程 » Chapter 四 Objects and Classes

Chapter 四 Objects and Classes  网友分享于:2013-02-19  浏览:3次
Chapter 4 Objects and Classes

1.    Encapsulation (sometimes called information hiding) is a key concept in working with objects. Formally, encapsulation is nothing more than combining data and behavior in one package and hiding the implementation details from the user of the object. A change in the state of an object must be a consequence of method calls.

2.    A simple rule of thumb in identifying classes is to look for nouns in the problem analysis. Methods, on the other hand, correspond to verbs.

3.    The most common relationships between classes are:
    a)    Dependence (“uses–a”)
    b)    Aggregation (“has–a”)
    c)    Inheritance (“is–a”)
A class depends on another class if its methods use or manipulate objects of that class. Try to minimize the number of classes that depend on each other. In software engineering terminology, you want to minimize the coupling between classes.


4.    UML Notation for Class Relationships

5.    It is important to realize that an object variable doesn’t actually contain an object. It only refers to an object. In Java, the value of any object variable is a reference to an object that is stored elsewhere. The return value of the new operator is also a reference.


6.    Local variables are not automatically initialized to null. You must initialize them, either by calling new or by setting them to null.


7.    When you use the Date class, the time is represented by the number of milliseconds (positive or negative) from a fixed point, the so called epoch, which is 00:00:00 UTC, January 1, 1970. UTC is the Coordinated Universal Time, the scientific time standard that is, for practical purposes, the same as the more familiar GMT or Greenwich Mean Time.


8.    The library designers decided to separate the concerns of keeping time and attaching names to points in time. Therefore, the standard Java library contains two separate classes: the Date class, which represents a point in time, and the GregorianCalendar class, which expresses dates in the familiar calendar notation. The job of a calendar is to compute attributes, such as the date, weekday, month, or year, of a certain point in time. The standard library does not contain any calendar implementations besides the Gregorian calendar.


9.    The Date class has only a small number of methods that allow you to compare two points in time (before() and after() ). Other methods of Date became deprecated when calendar classes were introduced.


10.    Methods that change instance fields are called mutator methods, and those that only access instance fields without modifying them are called accessor methods. A common convention is to prefix accessor methods with the prefix get and mutator methods with the prefix set.


11.    In Calendar, the months are counted from 0.

12.    Suppose you know the year, month, and day and you want to make a Date object with those settings. Since the Date class knows nothing about calendars, first construct a GregorianCalendar object and then call the getTime method to obtain a date. Conversely, if you want to find the year, month, or day of a Date object, construct a GregorianCalendar object, set the time, and then call the get method.


13.    There are varying conventions about the starting day of the week. In the United States, the week starts with Sunday and ends with Saturday, whereas in Europe, the week starts with Monday and ends with Sunday. The Java virtual machine is aware of the locale of the current user. The locale describes local formatting conventions, including the start of the week and the names of the weekdays. The getFirstDayOfWeek method of Calendar gets the starting weekday in the current locale.


14.    The getShortWeekdays method of DateFormatSymbols returns a string with short weekday names in the user’s language (such as "Sun", "Mon", and so on in English). The array is indexed by weekday values.


15.    The name of the java file must match the name of the public class. You can only have one public class in a source file, but you can have any number of nonpublic classes.


16.    When you type:
The Java compiler sees the Employee class being used inside, it will look for a file named Employee.class. If it does not find that file, it automatically searches for and compiles it. Moreover, if the timestamp of the version of that it finds is newer than that of the existing Employee.class file, the Java compiler will automatically recompile the file.


17.    In every method, the keyword this refers to the implicit parameter.


18.    Mutator methods can perform error checking, whereas code that simply assigns to a field may not go into the trouble.


19.    Be careful not to write accessor methods that return references to mutable objects. Always use clone whenever you need to return a copy of a mutable data field.


20.    A method can access the private data of all objects of its class, not just of the implicit parameter.


21.    You can define an instance field as final. Such a field must be initialized when the object is constructed. That is, you must guarantee that the field value has been set after the end of every constructor. Afterwards, the field may not be modified again.


22.    If you look at the System class, you will notice a method setOut that sets System.out to a different stream. You may wonder how that method can change the value of a final variable. However, the setOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround that you should not emulate in your programs.


23.    The Java programming language always uses call by value.


24.    The compiler must sort out which method to call. It picks the correct method by matching the parameter types in the headers of the various methods with the types of the values used in the specific method call. A compile-time error occurs if the compiler cannot match the parameters or if more than one match is possible. (This process is called overloading resolution.)


25.    If you don’t set a field explicitly in a constructor, it is automatically set to a default value: numbers to 0, boolean values to false, and object references to null.


26.    You get a free no-argument constructor only when your class has no other constructors.


27.    If the first statement of a constructor has the form this(. . .), then the constructor calls another constructor of the same class.


28.    Class declarations can contain arbitrary blocks of code, called initialization block. The initialization block runs first, and then the body of the constructor is executed.


29.    It is legal to set fields in initialization blocks even if they are only defined later in the class. However, to avoid circular definitions, it is not legal to read from fields that are only initialized later. We suggest that you always place initialization blocks after the field definitions.


30.    Here is what happens in detail when a constructor is called:
  a)    All data fields are initialized to their default values (0, false, or null).
  b)    All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
  c)    If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
  d)    The body of the constructor is executed.


31.    If the static fields of your class require complex initialization code, use a static initialization block. Place the code inside a block and tag it with the keyword static. Static initialization occurs when the class is first loaded. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration.


32.    The method call System.runFinalizersOnExit(true) guarantees that finalizer methods are called before Java shuts down. However, this method is inherently unsafe and has been deprecated. An alternative is to add “shutdown hooks” with the method Runtime.addShutdownHook.


33.    A class can use all classes from its own package and all public classes from other packages.


34.    You can only use the * notation to import a single package. You cannot use import java.* or import java.*.* to import all packages with the java prefix.


35.    Locating classes in packages is an activity of the compiler. The bytecodes in class files always use full package names to refer to other classes.


36.    A form of the import statement permits the importing of static methods and fields, not just classes. For example, if you add the directive:
    import static java.lang.System.*;
to the top of your source file, then you can use the static methods and fields of the System class without the class name prefix


37.    The compiler operates on files (with file separators and an extension .java), whereas the Java interpreter loads a class (with dot separators). The compiler does not check the directory structure when it compiles source files.


38.    Starting with version 1.2, the JDK implementors rigged the class loader to explicitly disallow loading of user-defined classes whose package name starts with "java.".


39.    Starting with Java SE 6, you can specify a wildcard for a JAR file directory in class path. All JAR files (but not .class files) in the specified JAR file directory are included in the class path. In UNIX, the * must be escaped as ‘*’ to prevent shell expansion.


40.    The javac compiler always looks for files in the current directory, but the java virtual machine launcher only looks into the current directory if the “.” directory is on the class path. If you have no class path set, this is not a problem—the default class path consists of the “.” directory.


41.    The class path lists all directories and archive files that are starting points for locating classes. The compiler has a harder time locating files than does the virtual machine. If you refer to a class without specifying its package, the compiler first needs to find out the package that contains the class. It consults all import directives as possible sources for the class. Then it searches for each of these classes in all of the locations of the class path. Classes must be unique, so the order of the import statements doesn’t matter.


42.    It is best to specify the class path with the -classpath (or -cp) option in java command.


43.    If your comments contain links to other files such as images (for example, diagrams or images of user interface components), place those files into a subdirectory of the directory containing the source file, named doc-files. The javadoc utility will copy the doc-files directories and their contents from the source directory to the documentation directory. You need to use the doc-files directory in your link, for example <img src="doc-files/uml.png" alt="UML diagram"/>.


44.    You can use hyperlinks to other relevant parts of the javadoc documentation, or to external documents, with the @see and @link tags.
    a)    @see reference adds a hyperlink in the “see also” section. It can be used with both classes and methods. The reference part can be one of the following:
        1)    package.class#feature label
        2)    <a href="...">label</a>
        3)    "text"
    For the first case, you supply the name of a class, method, or variable, and javadoc inserts a hyperlink to the documentation. For example, @see com.horstmann.corejava.Employee#raiseSalary(double). If the @see tag is followed by a < character, then you need to specify a hyperlink. You can link to any URL you like. In each of these cases, you can specify an optional label that will appear as the link anchor. If you omit the label, the user will see the target code name or URL as the anchor. If the @see tag is followed by a " character, then the text is displayed in the “see also” section.
    b)    You can place hyperlinks to other classes or methods anywhere in any of your documentation comments. Insert a special tag of the form:
    {@link package.class#feature label}
    anywhere in a comment. The feature description follows the same rules.


45.    To generate package comments, you need to add a separate file in each package directory. You have two choices:
    a)    Supply an HTML file named package.html. All text between the tags <body>...</body> is extracted.
    b)    Supply a Java file named The file must contain an initial Javadoc comment, delimited with /** and */, followed by a package statement. It should contain no further code or comments.


46.    You can also supply an overview comment for all source files. Place it in a file called overview.html, located in the parent directory that contains all the source files. All text between the tags <body>...</body> is extracted. This comment is displayed when the user selects “Overview” from the navigation bar.


47.    The javadoc program can be fine-tuned by numerous command-line options. You can use the -author and -version options to include the @author and @version tags in the documentation. (By default, they are omitted.) If you use the -linksource option, each source file is converted to HTML (without color coding, but with line numbers), and each class and method name turns into a hyperlink to the source. Another useful option is -link, to include hyperlinks to standard classes. Refer to for details.


48.    To produce documentation in a format other than HTML—you can supply your own doclet to generate the output in any form you desire. Refer to for details.


软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有