`
leonzhx
  • 浏览: 796617 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Chapter 2. Everything Is an Object -- Thinking in Java

阅读更多

1) Although it is based on C++, Java is more of a “pure” object-oriented language. Both C++ and Java are hybrid languages, but in Java the designers felt that the hybridization was not as important as it was in C++. A hybrid language allows multiple programming styles while the Java language assumes that you want to do only object-oriented programming.

 

2) Although you treat everything as an object, the identifier you manipulate is actually a “reference” to an object.

 

3) String s; Here you’ve created only the reference, not an object. If you decided to send a message to s at this point, you’ll get an error because s isn’t actually attached to anything. A safer practice, then, is always to initialize a reference when you create it: String s = "asdf"; However, this uses a special Java feature: Strings can be initialized with quoted text. Normally, you must use a more general type of initialization for objects. When you create a reference, you want to connect it with a new object. You do so, in general, with the new operator. The keyword new says, “Make me a new one of these objects.”

 

4) There are five different places to store data:

    a) Registers. This is the fastest storage because it exists in a place different from that of other storage: inside the processor. However, the number of registers is severely limited, so registers are allocated as they are needed. You don’t have direct control, nor do you see any evidence in your programs that registers even exist.

    b) The stack. This lives in the general random-access memory (RAM) area, but has direct support from the processor via its stack pointer. The stack pointer is moved down to create new memory and moved up to release that memory. This is an extremely fast and efficient way to allocate storage, second only to registers. The Java system must know, while it is creating the program, the exact lifetime of all the items that are stored on the stack. This constraint places limits on the flexibility of your programs, so while some Java storage exists on the stack—in particular, object references—Java objects themselves are not placed on the stack.

    c) The heap. This is a general-purpose pool of memory (also in the RAM area) where all Java objects live. The nice thing about the heap is that, unlike the stack, the compiler doesn’t need to know how long that storage must stay on the heap. Thus, there’s a great deal of flexibility in using storage on the heap. Whenever you need an object, you simply write the code to create it by using new, and the storage is allocated on the heap when that code is executed. Of course there’s a price you pay for this flexibility: It may take more time to allocate and clean up heap storage than stack storage.

    d) Constant storage. Constant values are often placed directly in the program code, which is safe since they can never change. Sometimes constants are cordoned off by themselves so that they can be optionally placed in read-only memory (ROM), in embedded systems. An example of this is the string pool. All literal strings and string-valued constant expressions are interned automatically and put into special static storage.

    e) Non-RAM storage. If data lives completely outside a program, it can exist while the program is not running, outside the control of the program. The two primary examples of this are streamed objects, in which objects are turned into streams of bytes, generally to be sent to another machine, and persistent objects, in which the objects are placed on disk so they will hold their state even when the program is terminated. The trick with these types of storage is turning the objects into something that can exist on the other medium, and yet can be resurrected into a regular RAM-based object when necessary. Java provides support for lightweight persistence, and mechanisms such as JDBC and Hibernate provide more sophisticated support for storing and retrieving object information in databases.

 

5) For “primitive” types, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and it’s placed on the stack, so it’s much more efficient.The reason for the special treatment is that to create an object with new—especially a small, simple variable—isn’t very efficient, because new places objects on the heap.

 

6) Java determines the size of each primitive type. These sizes don’t change from one machine architecture to another as they do in most languages. This size invariance is one reason Java programs are more portable than programs in most other languages.



 

 

7) All numeric types are signed. (char is not numeric.) The size of the boolean type is not explicitly specified; it is only defined to be able to take the literal values true or false. The “wrapper” classes for the primitive data types allow you to make a non-primitive object on the heap to represent that primitive type. Java SE5 autoboxing will automatically convert from a primitive to a wrapper type: Character ch = ‘x’; and back: char c = ch;

 

8) Java includes two classes for performing high-precision arithmetic: BigInteger and BigDecimal. Although these approximately fit into the same category as the “wrapper” classes, neither one has a primitive analogue. Both of them support arbitrary-precision numbers. ( for integers and decimals respectively)

 

9) A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The range checking comes at the price of having a small amount of memory overhead ( the length of the array and the data type the array holds) on each array as well as verifying the index at run time. When you create an array of objects, you are really creating an array of references, and each of those references is automatically initialized to a special value with its own keyword: null. You can also create an array of primitives. Again, the compiler guarantees initialization because it zeroes the memory for that array.

 

10) Scope determines both the visibility and lifetime of the names defined within it. In  Java, scope is determined by the placement of curly braces {}. A variable defined within a scope is available only to the end of that scope. Any text after a '//' to the end of a line is a comment. Since Java is a free-form language, the extra spaces, tabs, and carriage returns do not affect the resulting program.

 

11) You cannot do the following: { int x = 12; { int x = 96; // Illegal } } The compiler will announce that the variable x has already been defined.

 

12) Java objects do not have the same lifetimes as primitives. When you create a Java object using new, it hangs around past the end of the scope. Java has a garbage collector, which looks at all the objects that were created with new and figures out which ones are not being referenced anymore. Then it releases the memory for those objects, so the memory can be used for new objects.

 

13) The class keyword is followed by the name of the new type. For example:
class ATypeName { /* Class body goes here */ } This introduces a new type.

 

14) When you define a class, you can put two types of elements in your class: fields (sometimes called data members), and methods (sometimes called member functions). A field is an object of any type that you can talk to via its reference, or a primitive type. If it is a reference to an object, you must initialize that reference to connect it to an actual object.

 

15) When a primitive data type is a member of a class, it is guaranteed to get a default value if you do not initialize it:

   

 

  

16) The default values are only what Java guarantees when the variable is used as a member of a class. This ensures that member variables of primitive types will always be initialized. (The member variables of non-primitive types will always be initialized to null, if you don't initialize it.) However, this initial value may not be correct or even legal for the program you are writing. It’s best to always explicitly initialize your variables. This guarantee doesn’t apply to local variables—those that are not fields of a class. You are responsible for assigning an appropriate value before you use a variable. If you forget,  you will get a compile-time error telling you the variable might not have been initialized.

 

17) Methods in Java determine the messages an object can receive. The fundamental parts of a method are the name, the arguments, the return type, and the body. Here is the basic form:
ReturnType methodName( /* Argument list */ ) {
/* Method body */ }

The return type describes the value that comes back from the method after you call it. The argument list gives the types and names for the information that you want to pass into the method. The method name and argument list (which is called the signature of the method) uniquely identify that method. Methods in Java can be created only as part of a class.

 

18) What you must specify in the argument list are the types of the objects to pass in and the name to use for each one. As in any situation in Java where you seem to be handing objects around, you are actually passing references. The type of the reference must be correct.

 

19) return keyword does two things. First, it means “Leave the method, I’m done.” Second, if the method produces a value, that value is placed right after the return statement. You can return any type you want, but if you don’t want to return anything at all, you do so by indicating that the method returns void. When the return type is void, then the return keyword is used only to exit the method, and is therefore unnecessary when you reach the end of the method.

 

20) To produce an unambiguous name for a library, the Java creators want you to use your Internet domain name in reverse as your package name since domain names are guaranteed to be unique. By convention the entire package name is lowercase.

 

21) If a class already exists in the same source-code file that it’s being called from, you can simply use the class—even if the class doesn’t get defined until later in the file (Java eliminates the so-called “forward referencing” problem).

 

22) You must eliminate all potential ambiguities. This is accomplished by telling the Java compiler exactly what classes you want by using the import keyword. import tells the compiler to bring in a specified and unique class or a package(by using '*'), which is a library of classes.

 

23) It is more common to import a collection of classes in this manner than to import classes individually. This is easily accomplished by using '*'  to indicate a wild card:
import java.util.*;

 

24) When you say something is static, it means that particular field or method is not tied to any particular object instance of that class. So even if you’ve never created an object of that class you can call a static method or access a static field. With ordinary, non-static fields and methods, you must create an object and use that object to access the field or method, since non-static fields and methods must know the particular object they are working with. To make a field or method static, you simply place the keyword before the definition.

 

25) Of course, since static methods don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object (since non-static members and methods must be tied to a particular object).

 

26) There are two ways to refer to a static variable. You can name it via an object or you can also refer to it directly through its class name, something you cannot do with a non-static member. Using the class name is the preferred way to refer to a static variable. Not only does it emphasize that variable’s static nature, but in some cases it gives the compiler better opportunities for optimization.

 

27) Although static, when applied to a field, definitely changes the way the data is created (one for each class versus the non-static one for each object), when applied to a method it’s not so dramatic. An important use of static for methods is to allow you to call that method without creating an object.

 

28) At the beginning of each program file, you must place any necessary import statements to bring in extra classes you’ll need for the code in that file. There’s a certain library of classes that are automatically brought into every Java file: java.lang.*.

 

29) The name of the class is the same as the name of the file. When you’re creating a standalone program, one of the classes in the file must have the same name as the file. (The compiler complains if you don’t do this.)

 

30) There are two types of comments in Java. The first is the traditional C-style comment that was inherited by C++. These comments begin with a /* and continue, possibly across many lines, until a */. The second form of comment comes from C++. It is the single-line comment, which starts with a // and continues until the end of the line.

 

31) The easiest way to link the code to the documentation is to put everything in the same file. To complete the picture, however, you need a special comment syntax to mark the documentation and a tool to extract those comments and put them in a useful form. This is what Java has done. The tool to extract the comments is called javadoc, and it is part of the JDK installation. It uses some of the technology from the Java compiler to look for special comment tags that you put in your programs. It not only extracts the information marked by these tags, but it also pulls out the class name or method name that adjoins the comment. This way you can get away with the minimal amount of work to generate decent program documentation. In addition, you can write your own Javadoc handlers, called doclets, if you want to perform special operations on the information processed by javadoc.

 

32) All of the javadoc commands occur only within /** comments. The comments end with */ as usual. There are two primary ways to use Javadoc: Embed HTML or use “doc tags.” Standalone doc tags are commands that start with an @ and are placed at the beginning of a comment line. (A leading '*' , however, is ignored.) Inline doc tags can appear anywhere within a javadoc comment and also start with an @ but are surrounded by curly braces.

 

33) There are three “types” of comment documentation, which correspond to the element the comment precedes: class, field, or method. That is, a class comment appears right before the definition of a class, a field comment appears right in front of the definition of a field, and a method comment appears right in front of the definition of a method.

 

34) javadoc will process comment documentation for only public and protected members. Comments for private and package-access members are ignored, and you’ll see no output. (However, you can use the -private flag to include private members as well.)

 

35) javadoc passes HTML commands through to the generated HTML document. This allows you full use of HTML. Note that within the documentation comment, asterisks at the beginning of a line are thrown away by Javadoc, along with leading spaces. Don’t use headings such as <h1> or <hr> as embedded HTML, because Javadoc inserts its own headings and yours will interfere with them.

 

36) @see tag allows you to refer to the documentation in other classes. javadoc will generate HTML with the @see tags hyperlinked to the other documentation. The forms are:
@see classname
@see fully-qualified-classname
@see fully-qualified-classname#method-name

Each one adds a hyperlinked “See Also” entry to the generated documentation.

 

37) {@link package.class#member label} Very similar to @see, except that it can be used inline and uses the label as the hyperlink text rather than “See Also.”

 

38) {@docRoot} produces the path to the documentation root directory. Useful for explicit hyperlinking to pages in the documentation tree.

 

39) {@inheritDoc} inherits the documentation from the nearest base class of this class into the current doc comment.

 

40) @version version-information in which version-information is any significant information you see fit to include. When the -version flag is placed on the javadoc command line, the version information will be called out specially in the generated HTML documentation.

 

41) @author author-information  in which author-information is, presumably, your name, but it could also include your email address or any other appropriate information. When the -author flag is placed on the Javadoc command line, the author information will be called out specially in the generated HTML documentation. You can have multiple author tags for a list of authors, but they must be placed consecutively. All the author information will be lumped together into a single paragraph in the generated HTML.

 

42) @since tag allows you to indicate the version of this code that began using a particular feature. You’ll see it appearing in the HTML Java documentation to indicate what version of the JDK is used.

 

43) @param parameter-name description is used for method documentation,
in which parameter-name is the identifier in the method parameter list, and description is text that can continue on subsequent lines. The description is considered finished when a new documentation tag is encountered. You can have any number of these, presumably one for each parameter.

 

44) @return description This is used for method documentation, in which description gives you the meaning of the return value. It can continue on subsequent lines.

 

45)@throws fully-qualified-class-name description in which fully-qualified-class-name gives an unambiguous name of an exception class that’s defined somewhere, and description (which can continue on subsequent lines) tells you why this particular type of exception can emerge from the method call.

 

46) @deprecated This is used to indicate features that were superseded by an improved feature. The deprecated tag is a suggestion that you no longer use this particular feature, since sometime in the future it is likely to be removed. A method that is marked @deprecated causes the compiler to issue a warning if it is used. In Java SE5, the @deprecated javadoc tag has been superseded by the @Deprecated annotation.

 

47) The style described in the Code Conventions for the Java Programming Language is to capitalize the first letter of a class name. If the class name consists of several words, they are run together (that is, you don’t use underscores to separate the names), and the first letter of each embedded word is capitalized. This is sometimes called “camel-casing.” For almost everything else—methods, fields (member variables), and object reference names—the accepted style is just as it is for classes except that the first letter of the identifier is lowercase.

 

  • 大小: 72.4 KB
  • 大小: 16.7 KB
  • 大小: 25.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics