2. To work with OOP, you should be able to identify three key characteristics of objects:
- The object’s behavior—what can you do with this object, or what methods can you apply to it?
- The object’s state—how does the object react when you invoke those methods?
- The object’s identity—how is the object distinguished from others that may have the same behavior and state?
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 ( or LocalDate class introduced in
Java 8), 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. (Calendar.Sunday = 1)
14. The getShortWeekdays method of DateFormatSymbols returns an array of 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:
javac EmployeeTest.java
The Java compiler sees the Employee class being used inside EmployeeTest.java, it will look for a file named Employee.class (starting from the current path where javac is invoked). If it does not find that file, it automatically searches for Employee.java and compiles it. Moreover, if the timestamp of the version of Employee.java 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 (It can only be initialized once.). 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 term call by value means that the method gets just the value that the caller provides. In contrast, call by reference means that the method gets the location of the variable that the caller provides. Thus, a method can modify the value stored in a variable passed by reference but not in one passed by value. 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 reference/read fields that are 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 ( but it will lookup the dependent source file following the directory structure, see item 16).
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 such as /home/user/archives/'*' in UNIX or c:\archives\* in Windows. All JAR files (but not .class files) in the archives 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. The runtime library files (rt.jar and the other JAR files in the jre/lib and jre/lib/ext directories) are always searched for classes first.
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, 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 package-info.java. 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. To type monospaced code, use {@code ... } instead of <code>...</code>.
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: javadoc -d outputDir -link http://docs.oracle.com/javase/8/docs/api *.java
For other options refer to http://docs.oracle.com/javase/8/docs/technotes/guides/javadoc/.
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 http://docs.oracle.com/javase/8/docs/technotes/guides/javadoc/doclet/overview.html for details.
49. Class Design Hints:
a) Always keep data private.
b) Always initialize data.
c) Don’t use too many basic types in a class.
d) Not all fields need individual field accessors and mutators.
e) Break up classes that have too many responsibilities.
f) Make the names of your classes and methods reflect their responsibilities.
50. LocalDate.now() constructs a new object that represents the date at which the object was constructed. You can construct an object for a specific date by supplying year, month, and day :
LocalDate.of(1999, 12, 31). You can find out the year, month, and day with the methods getYear, getMonthValue, and getDayOfMonth. The plusDays method yields a new LocalDate that is a given number of days away from the object to which you apply it.
51. We call the getValue method of DayOfWeek object to get a numerical value for the weekday. This yields an integer that follows the international convention where the weekend comes at the end of the week, returning 1 for Monday, 2 for Tuesday, and so on. Sunday has value 7.
52. Local variables shadow the instance fields with the same name. You have to be careful in all of your methods to not use variable names that equal the names of instance fields.
53. You can think of static methods as methods that don’t have a this parameter.
54. Since Java SE 7, the java program first checks that there is a main method before executing the static initialization block.
55. From the point of view of the compiler, there is absolutely no relationship between nested packages. For example, the packages java.util and java.util.jar have nothing to do with each other. Each is its own independent collection of classes.
56. The compiler does not check the directory structure whether it matches the package declaration when it compiles source files.
57. The javadoc utility extracts information for the following items:
- Packages
- Public classes and interfaces
- Public and protected fields
- Public and protected constructors and methods
58. The class comment must be placed after any import statements, directly before the class definition. Each method comment must immediately precede the method that it describes. @param tag adds an entry to the “parameters” section of the current method. @return tag adds a “returns” section to the current method. @throws tag adds a note that this method may throw an exception.
没有评论:
发表评论