Thinking in Java 3

zhaozj2021-02-11  196

Chapter 2 Everything is an object

"Although based on C , Java is a more pure object-oriented programming language."

Regardless of C or Java is a hybrid language. But in Java, the designer feels that this hybrid is not like this in C . Hybrid language allows multiple programming styles; C is a hybrid language because it supports backward compatibility with C language. Since C is a supercoming of C, many of the features included are not available, these features make C more complicated in some places.

Java language first assumes that we only want to perform object-oriented programming. That is to say, before formal use of its design, you must first transfer your idea into an object-oriented world (unless you are accustomed to this world thinking). Only by doing this preparation, you can experience Java's easy-to-use. In this chapter, we will explore the basic components of the Java program, and experience everything in Java and even Java programs is an object.

2.1 Manipulate the object with handle

Every programming language has its own data processing. Sometimes, the programmer must always pay attention to what type of preparation processing. You have used some special syntax to operate the object directly, or handle some indirectly represented objects (C or C pointers)?

All of these have been simplified in Java, and anything can be seen as an object. Therefore, we can use a unified syntax, anywhere can be caught incorrectly. But note that although all "see" objects, the manipulated identifier is actually pointing to a "handle" of an object. In other Java reference books, you can also see some people call it as a "reference", even a "pointer". This scenario is imagined using a remote control board (handle) to manipulate the television (object). As long as this remote control board is held, it is equivalent to mastering the channel connected to the TV. But once you need "Change Channel" or "Tight Sound", we actually manipulate the remote control board (handle), and then manipulate the TV (object) itself. If you want to walk around the room and want to keep the control of the TV, then hold the remote control board, not a TV.

In addition, even if there is no TV, the remote control can also be independently present. That is, since there is a handle, it does not mean that there must be an object to connect to it. So if you want to accommodate a word or sentence, create a String handle:

String S;

But here is only a handle, not an object. If you send a message to S, an error (running period) is obtained. This is because S is not connected to anything (ie "no TV"). Therefore, a more secure approach is: When you create a handle, remember to initialize anyway:

String s = "ASDF";

However, here is a special type: the string can be initialized by the text of the quotation number. Typically, a more general initialization type must be used for an object.

2.2 All objects must be created

When you create a handle, we hope that it will connect to the same new object. This is usually used to achieve this with the new keyword. New meaning: "Types me into a new type of these objects." So in the example above, it can be said:

String s = new string ("ASDF");

It not only pointed out that "how to become a new string", but also to provide an initial string, pointing out "How to Generate this new string". Of course, string is not unique. Java support provides a large number of ready-made types. For us, the most important thing is to remember to create a type you can. In fact, this should be a basic operation of the Java program design, which is the basis for continuing the posts in the rest of this book.

2.2.1 Save to where

When the program is running, we'd better save the data to where you have a number. It is important to pay attention to the distribution of memory. Six places can save data:

(1) Register. This is the fastest storage area because it is located in different places in all other saving methods: the internal processor. However, the number of registers is very limited, so the register is assigned by the compiler as needed. We have no direct control of this, or it is impossible to find any traces in the register in your own program.

(2) Stack. Reside on regular RAM (Random Access Memory) area, but can be processed directly through its "stack pointer". If the stack pointer moves down, a new memory will be created; if you move, you will release those memory. This is a very fast, particularly effective data storage method, second only to the register. When you create a program, the Java compiler must accurately know "length" and "existing time" of all data saved in the stack. This is because it must generate the corresponding code to move the pointer up and down. This limitation undoubtedly affects the flexibility of the program, so although some Java data should be saved in the stack - especially the object handle, the Java object does not place it.

(3) Heap. A conventional use of memory pool (also in the RAM area), which saves Java objects. Unlike the stack, "Memory" or "Heap" The most attractive place is that the compiler does not have to know how much storage space is to be allocated from the heap, and you don't have to know how long the stored data is to stay in the stack. Therefore, greater flexibility is obtained when saving data with a stack. When you create an object, just use the new command to prepare the relevant code. When you perform these code, you will automatically save the data in the stack. Of course, in order to achieve this flexibility, it will inevitably pay a certain price: it will take a longer time when allocating the storage space!

(4) Static storage. "Static" here refers to "located in a fixed position" (although in the RAM). During the operation, the static stored data will wait any time. The STATIC keyword can be used to indicate a particular element of an object is static. But the Java object itself will never place static storage.

(5) constant storage. The constant value is usually placed inside the program code. This is safe because they will never change. Some constants need to be strictly protected, so they can consider placing them into read-only memory (ROM).

(6) Non-RAM storage. If the data is completely independent of a program, the program can still be present when the program is not running, and outside the program's control range. Two of the most important examples are "flow objects" and "fixed objects". For streaming objects, the object will become byte stream, which is usually sent to another machine. For fixed objects, the object is saved in the disk. They still keep their own status unchanged even if the program is aborted. For these types of data stores, a particularly useful technique is that they can exist in other media. Once needed, they can even return them into ordinary, RAM-based objects. Java 1.1 provides support for LightWeight Persistence. Future versions may even provide a more complete solution.

2.2.2 Special circumstances: Main types

A series of columns need to be treated; they can imagine them into "basic", "primary" or "primitive) type, and it is necessary to use them frequently when the program is designed. It is not very effective because of the use of New Creating objects (especially small, simple variables), because NEW places objects in "stack". For these types, Java adopts the same method as C and C . That is, it is not to create a variable with NEW, but create an "automatic" variable of the handle. This variable accommodates the specific value and placed in the stack to access more efficiently. Java determines the size of each primary type. As in most languages, these sizes do not change as the machine structure changes. This size of this size is one of the reasons why Java programs have strong portability.

Main type size minimum maximum wrapping type

Boolean 1 - Boolean

Char 16-bit Unicode 0 Unicode 2 16th party -1 Character

BYTE 8-128 127 byte (Notes 1)

Short 16-bit-2 15th 2 15th party -1 Short (Notes 1)

INT 32-2-2 31 2 31 -1 INTEGER

LONG 64-bit-2 63 2 63 -1 -1 LONG

Float 32-bit IEEE754 IEEE754 FLOAT

Double 64-bit IEEE754 IEEE754 DOUBLE

Void - - - Void (Notes 1)

1: That is to Java 1.1, the version 1.0 is not.

The numerical types are all symbol (positive and negative), so do not have to find a type without symbols.

The primary data type also has its own "wrapper" class. This means that if a non-primary object in the stack indicates that the main type is to use the corresponding package. E.g:

CHAR C = 'x';

Character C = New Character ('c');

You can also use it directly:

Character C = New Character ('x');

The reason why this will be explained in the later chapter.

High precision number

Java 1.1 adds two classes to perform high-precision calculations: Biginteger and BigDecimal. Although they can be roughly divided into a "package" type, there is no corresponding "main type".

Both classes have their own special "methods", corresponding to the operations we perform for main types. That is to say, things that can be done to int or float can do the same as Biginteger and BigDecimal. Just use the method call and cannot use the operator. In addition, due to more, the calculation speed will be slow. We sacrifice the speed, but exchanged accuracy.

Biginteger supports an integer of any precision. That is, we can accurately represent any integer value of the size and will not lose any information during the operation.

BigDecimal supports a fixed-point number of any precision. For example, it can be calculated using it for accurate coins.

For builders and methods available when calling these two classes, please refer to the online help documentation.

2.2.3 A number of java

Almost all programming languages ​​support arrays. It is very dangerous to use arrays in C and C because those arrays are just memory blocks. If the program accesses an array other than the memory block, or before initialization (belonging to a regular programming error), it will generate unpredictable consequences (annotation 2). 2: In C , try not to use an array, for a safer container in Standard TemplateLibrary.

One of Java's main design goals is security. So many problems in the C and C are not repeated in Java. A Java ensures that it is initialized and cannot be accessed outside of its range. Since the system automatically performs range check, there must be some cost: for each array, and the verification of the index during operation, it will cause a small amount of memory overhead. However, it is more secure and higher work efficiency. Paying a little price for this.

When you create an object array, you actually created a handle array. And each handle is automatically initialized into a special value and has its own keywords: null. Once Java see NULL, you know that the handle does not point to an object. Before formal use, you must assign an object for each handle. If you try to use a handle that is still NULL, you will report a problem in the runtime. Therefore, typical array errors are avoided in Java.

You can also create a primary type array. Similarly, the compiler guarantees initialization to it because the memory score of that array is divided into zero.

Array issues will be discussed in detail in the subsequent chapters.

2.3 Never clear the object

In most programming languages, the "Lifetime" of the variable has been a problem that programmers need to be considered. How long should variables continue? If you want to clear it, when is it going? There is a large number of program errors in the presence of variables. In the following subsections, Java will explain how Java helps us complete all clear work, which greatly simplifies this problem.

2.3.1 Scope

Most programming languages ​​provide the concept of "scope". For the name defined in the scope, the scope also determines its "visibility" and "existing time". In C, C , and Java, the scope is determined by the position of the curly bracket. Refer to the following example:

73Player

As a variable defined in the scope, it can only be used before that scope ends.

In the above example, the retracted typeset makes the Java code more readily read. Since Java is a form of freedom language, additional spaces, analyte, and carriage return will not affect the results procedures.

Note that although it is legal in C and C , it cannot be written in Java.

Page 74

The compiler will consider variable X has been defined. So C and C can "hide" in a larger scope in a larger scope. But this approach is not allowed in Java, as Java designers think this makes the program confused.

2.3.2 Scope of the object

Java objects do not have the same time as the primary type. When you create a Java object with the New keyword, it will exceed the scope of the scope. So if you use the following code:

{

String S = New String ("a string");

} / * The end point of the scope * /

The handle S disappears at the end of the scope. However, String objects pointing to the String still occupies the memory space. In this code, we have no way to access objects because the only handle pointing to it has exceeded the boundaries of the scope. In the later chapter, everyone will continue to learn how to pass and copy object handles during the program run. The result of this is: For objects created with New, as long as we are willing, they will keep it. This programming problem is particularly highlighted in C and C . It seems that the biggest troubles encountered in C : Since it is not possible to get any help from the language, it is not possible to determine if they need to be available. And more troublesome is that in C , once the work is completed, it must be cleared.

This brings an interesting question. If Java is still the object, how can I prevent them from flooding a lot, and eventually cause "solidification" of the program. In C , this problem has the most programment headache. But after Java, the situation has changed. Java has a special "garbage collector" that looks for all objects created with New and identifies which of them no longer referenced. Subsequently, it will automatically release the memory occupied by those idle objects so that it can be used by new objects. This means that we don't have to worry about memory recovery. Simply create an object, once they no longer need them, they will automatically leave. Doing so can prevent a very common programming problem in C : Since the programmer forgets "memory overflow" caused by memory.

2.4 New Data Type: Class

If everything is an object, then what to determine a "class" (Class) look and behavior? In other words, what is the establishment of an object's "type" (TYPE)? Everyone may guess a keyword called "Type". But from history, most of the object-oriented languages ​​use keyword "class" to express this means: "I am going to tell you an object a new type of look." The Class keyword is often used, so that many places in this book are not emphasized with crude characters or double quotes. Behind this keyword, you should follow the name of the new data type. E.g:

Class atypename {/ * class body is placed here}

This introduces a new type, next to NEW to create a new object of this type:

Atypename a = new atypename ();

In atypename, the class body is constructed only by one annotation (asterisk and slash, and the contents thereof), which will not be detailed behind this chapter), so there is not much to do too much. In fact, you can't indicate anything at all unless certain methods are defined.

2.4.1 Fields and Methods

When defining a class (all of our jobs in Java are defined classes, making the objects of those classes, sending messages to those objects), set two types of elements in their own classes: Data members (sometimes called " Field ") and member functions (usually called" method "). Among them, the data member is an object (via its handle and its communication), can be any type. It can also be one of the main types (not the handle). If it is a handle to the object, the handle must be initialized, and a special function named "Builder" (detailed in Chapter 4 will be connected to an actual object (just as you can see you first. Then use the new keyword). But if it is a primary type, you can directly initialize the class definition position (as will be seen later, the handle can also be initialized). Each object has storage space for its own data; data members are not shared between objects. Below is a class example that defines some data members:

Page 76

This class does not do any substantive thing, but we can create an object:

Dataonly D = new data iONLY ();

You can assign a value to a data member, but you must first know how to reference a member of an object. In order to reach the purpose of the reference object member, you must first write the name of the object handle, follow one point (period), follow the name of the object inside the object. That is, "object handle. Member". E.g:

D.i = 47;

D.f = 1.1f;

D.B = false;

An object may also contain another object, and another object contains the data we want to modify. For this problem, just keep the "connection period". E.g:

Myplane.Lefttank.capacity = 100;

In addition to accommodating data, the DataOnly class can no longer do more things because it does not have a member function (method). To correctly understand the working principle, you must first know the concept of "argument" and "return value". We will immediately explain it.

1. The default value of the main member

If a primary data type belongs to a class member, then even if it is not clear (explicit), it can also guarantee a default value.

Main type default value

Boolean False

Char '/ u0000' (NULL)

Byte (byte) 0

SHORT (Short) 0

Int 0

Long 0L

Float 0.0F

Double 0.0D

Once the variable is used as a class member, pay special attention to the default value assigned by Java. This must ensure that the member variable of the primary type will definitely be initialized (C does not have this feature), which can effectively curb a variety of related programming errors.

However, this guarantee is not suitable for "local" variables - those variables are not a class of fields. So, if you write the following code in a function definition:

INT X;

Then x will get some random values ​​(this is the same as C and C ), which will not initialize zero. Our responsibility is to assign an appropriate value before formal using X. If you forget, you will get a compile time error, tell us that the variable may have not been initialized. This treatment is one of the performance of Java better than C . Many C compilers will issue a warning for variables that are not initialized, but they are errors in Java.

2.5 Method, argument and return value

To date, we have been using the word "function" to refer to a named subroutine. But in Java, one of the more commonly used words is "Method", represents "The Way to Complete Something". Although they are actually the same, since now, this book will always use "method" instead of "function." Java's "Method" determines the message that an object can receive. Through this section, everyone will know how simple is the definition of the method!

The basic components of the method include name, argument, return type, and body. The following is its most basic form:

Return Type method (/ * Self-variable list * /) {/ * method body * /}

The return type is the type of value returned after the adjustment method. Obviously, the role of the method name is to identify and reference for specific methods. The variable list lists the types and names that want to pass to the method.

Java's way can only be created as part of the class. You can only call a method (annotation 3) for an object, and that object must be able to perform that method call. If you try to call an error in an object, you will get an error message in the compile period. When calling a method for an object, you need to list the name of the object, follow the next period, follow the top of the above, and its parameter list. That is, "object name. Method name (self-variable 1, self-variable 2, self-variable 3 ...). To put it, suppose we have a method named f (), it has no argument, returning is A value of type Int. So, assume that there is an object called A, which can call method f (), the code is as follows:

INT x = a.f ();

The type of return value must be compatible with the type of X.

Action like this calling a method is typically called "send a message to the object." In the above example, the message is f (), and the object is a. Object-oriented programming is often simply summarized as "to send messages to objects".

3: As soon as you want to learn, the "static" method can call the class, there is no need for an object.

2.5.1 List of variables

The list of variables specifies what information we are transmitted to the method. As everyone may be guessed, this information is like anything in Java - all the form of objects. Therefore, we must specify the type of object to be passed in the argument list, and the name of each object. As in Java other places to handle objects, we actually passed "handle" (annotation 4). However, the type of handle must be correct. If you want the argument to be a "string", the passing must be a string.

4: It is an exception to the "Special" data type Boolean, Char, Byte, Short, Int,, long, float, and double mentioned in the previously mentioned. However, when the object is transmitted, it is usually referred to whether the handle of the pass pointing object is transmitted.

Let us consider the method of using a string as an argument. The following is the definition code, and it must be placed in a class definition, otherwise you cannot compile:

Int Storage (string s) {

Return S.Length () * 2;

}

This method tells us how many bytes need to accommodate information in a particular string (each character in the string is 16 bits, or 2 bytes, long integers to provide support for Unicode characters). The type of argument is String and is called S. Once the S is passed to the method, it can be processed as other objects (send messages to it). Here, we call the Length () method, which is one of the String methods. The method returns to the number of characters in a string. By the above example, you can also understand the use of the Return keyword. It mainly does two things. First of all, it means "leaving the method, I have finished". Second, hypothesis is a value generated, then that value is followed by the return statement. In this case, the return value is generated by calculating the expression "s.length () * 2".

You can return any type according to your own wish, but if you don't want to return anything, you can indicate that the method returns Void (empty). Some examples are listed below.

Boolean flag () {return true;}

FLOAT NATuralLogbase () {Return 2.718;}

Void Nothing () {return;

Void Nothing2 () {}

If the type is VOID, the only role of the Return keyword is to exit the method. So once the arrival method is at the end of the method, the keyword does not need. It can be returned from one way anywhere. However, it is assumed that a non-VOID return type has been specified, then the compiler will ensure that the compiler will ensure that we return is the correct type regardless of wherever returned.

To this end, everyone may have got an impression: A program is just a collection of objects, and their methods use other objects as their own arguments and send messages to those objects. This kind of saying is generally correct, but through future learning, everyone will know how to make decisions in a method, do some more detailed grassroots work. As for this chapter, it is enough to understand the message transmission.

2.6 Build a Java program

There are several questions that need to be paid before formally build your first Java program.

2.6.1 visibility of the name

In all programming languages, an inevitable problem is the control of the name or name. Suppose you use a name in a module in the program, and another programmer uses the same name in another module. At this time, how to distinguish between two names and prevent two names from conflicting to each other? This issue is particularly prominent in C language. Because the program does not provide a good name management method. C class (ie, the basis of the Java class) Nested the function in the class, so that it does not conflict with nested functions in other classes. However, C still allows global data and a global function, so it is still difficult to avoid conflicts. To solve this problem, C introduces the concept of "named space" with additional keywords.

Java can completely avoid these problems due to the new mechanism. In order to generate a clear name to a library, a name similar to the Internet domain name is used. In fact, Java designers encourage programmers to reverse using their own Internet domain name because they are definitely unique. Since my domain name is Bruceeckel.com, I can name com.bruceeckel.utility.foibles. Once the domain name is reversed, you can imagine a child directory.

In Java 1.0 and Java 1.1, the domain extension COM, EDU, ORG, NET, etc. are set to uppercase. Therefore, the look of the library becomes: com.bruceeckel.utility.foibles. However, during the development of Java 1.2, the designer finds that this will cause some problems. So the current whole package is based on lowercase letters. This special mechanism for Java means that all files are automatically present in their namespace. And each class in a file is automatically got a unique identifier (of course, the class name in a file must be unique). So don't have to learn special language knowledge to solve this problem - the language itself has helped us take care of this.

2.6.2 Using other components

Once you want to use a predefined class in your own program, the compiler must know how to find it. Of course, this class may be in the same source code file that is called. If this is the case, simply use this class - even if it is not defined behind the file. Java eliminates the "forward reference" problem, so don't care about these things.

But if the class is in other files? You may think that the compiler should be enough to "alliance", you can discover it yourself. But the truth is not the case. Suppose we want to use a class with a specific name, but the definition of that class is located in multiple files. Or worse, suppose we are ready to write a program, but when you create it, add a new class to your own library, which conflicts with the name of the existing class.

To solve this problem, you must eliminate all potential and entangled. To achieve this, use the import keyword to accurately tell the Java compiler what we hope. Import's role is to indicate that the compiler is imported into a "package" - or a "class library" (in other languages, "library" can imagine a set of functions, data, and class. But remember, Java All code must be written in a class).

Most of the time we use components (components) from standard Java libraries, they are provided with compiler. When using these components, there is no need to care about lengthy reserved domain names; for example, just write a line of code below:

Import java.util.vector;

Its role is to tell the compiler that we want to use Java's Vector class. However, Util contains a large number of classes, and we sometimes want to use several, while do not want to clear them clearly. To achieve this purpose, you can use the "*" wildcard. As follows:

Import java.util. *;

It is usually used when you need to import a range of classes. One way should be avoided to be imported into the class.

2.6.3 static keyword

Typically, when we create classes, you will point out the appearance and behavior of the object of the class. Unless I created one object of that class with NEW, I actually didn't get anything. Data storage is formally generated after NEW, and the corresponding method can be used.

However, in two special circumstances, the above method is not available. One situation is just to use a storage area to save a specific data - no matter how many objects to create, even simply do not create objects. Another situation is that we need a special method that does not associate any objects of this class. That is to say, even if the object is not created, a method of calling can be called. To meet these two requirements, STATIC keywords can be used. Once there is something set to static, data or methods, it will not be contacted with any object instances of the class. So although an object that has never created that class, you can still call a static method or access some STITIC data. Before this, for non-Static data and methods, we must create an object and use that object to access data or methods. This is because non-Static data and methods must know the specific objects they operate. Of course, before formal use, because the Static method does not need to create any object, they cannot simply call other members, and do not reference a named object, thereby directly accessing non-Static members or methods (because non-Static members and methods You must associate together with a specific object). Some object-oriented languages ​​use two terms that "class data" and "class methods". They mean that data and methods exist as a whole class, not any particular object for that class. Sometimes you discover such a name in some other Java books.

In order to set the data member or method to Static, simply need to define the preamp and this keyword. For example, the following code can generate a STITIC data member and initialize it:

Class stat Arttest {

Static int i = 47;

}

Now, although we have made two StaticTest objects, they still only occupy a storage space of StaticTest.i. Both objects share the same i. Please examine the following code:

StaticTest ST1 = New Statictest ();

StaticTest ST2 = New Statictest ();

At this time, both ST1.I is also ST2.I, the same value 47 is, since they are referenced to the same memory area.

There are two ways to reference a static variable. As shown above, you can name it through an object, such as st2.i. It can also be used directly with its class name, and this is not working in non-statist members (it is best to use this method to reference the static variable because it emphasizes the "static" essence of that variable).

Statictest.i ;

Where operators will increase the variable. At this time, no matter the value of ST1.I or St2.i, it is 48.

Similar logic is also suitable for static methods. You can use a special grammar format "class name. Method ()" by a special grammatical format. Method (). The definition of a static method is similar:

Class staticfun {

Static void incr () {statictest.i ;}

}

As can be seen, StaticFun's method INCR () increases the static data I. Through the object, INCR ():

StaticFun sf = new staticfun ();

sf.incr ();

Alternatively, since INCR () is a static method, it can be directly called by its class:

Staticfun.incr ();

Although it is "static", as long as it is applied to a data member, it will clearly change the creation of data (a class member, and a non-statist member of each object). If it is applied to a method, it is not so drama. For the method, Static an important use is to help us call the method without having to create an object. As will be seen later, this is crucial - especially when defining the program running portal method main (). Like any other method, the Static method can also create its own type of named object. So often use the Static method as a "leader", use it to generate a series of "instances".

2.7 Our first Java program

Finally, let us officially edit a program (note 5). It can print out information related to the currently running system and utilize a variety of ways from the SYSTEM object from the Java standard library. Note that an additional annotation style is introduced here: "//". It indicates that all content before the end of the Bank is comments:

84-page program

5: In some programming environments, the program will pass everything on the screen, and even have no chance to see the result. The following code can be placed at the end of Main (), and it is suspended from the output:

Try {

Thread.currentthread (). Sleep (5 * 1000);

} catch (interruptedexception e) {}

}

Its role is to pause the output for 5 seconds. Some concepts involved in this code are going to this book later. So there is no need to study, just know that it is a skill that is suspended.

At the beginning of each program file, you must place an Import statement to import all the extra classes you want to use in the code of the file. Note We say they are "extra" because a special class library will automatically import each Java file: java.lang. Start your web browser to view user documents provided by Sun (if you have not downloaded from http://www.java.sun.com, or use other ways to install Java documentation, download now). In the packages.html file, you can find all the library names provided by the Java support. Please select the java.lang. Below "Class Index", you can find a list of all classes belonging to that library. Since java.lang enters each Java code file by default, these classes can be used directly at any time. In this list, you can find SYSTEM and RUNTIME, we used them in Property.java. Date classes are not listed in java.lang, so you must import another class library to use it. If you don't know which class library in a particular class, or want to view all classes, select "Class Hierarchy" in the Java User Document. In a web browser, although it is not short to establish this structure, you can clearly find every class supplied with Java. Subsequently, you can search the keyword "date" with the "Find" function of the browser. After doing so, we can find that our search target is listed in java.util.date. We finally know that it is located in Util Curre, so you must import java.util. *; Otherwise you can't use Date.

Observe the top of the package. Html document (I have set it to your default start page), select Java.lang, select System. At this time, you can see a few fields in the SYSTEM class. If you choose OUT, you can know that it is a Static PrintStream object. Since it is "static", we don't need to create anything. Out objects are definitely 3, so just use it directly. What we can do for this OUT object is determined by its type: PrintStream. PRINTSTREAM lists in the form of a hyperlink in a hyperlink, which is very convenient. Therefore, if you click the link, you can see all the methods that can be called for the PrintStream. The number of methods is a lot, and the book will be described in detail later. As far as we are interested in println (). It means "printing me to your constended, and ending with a new line". So in any Java program, once some content is printed onto the console, you can write SYSTEM.OUT.PRINTLN ("Content"). The class name is the same as the file. If you create a separate program now, a class in the file must be the same name with the file (if it doesn't do this, the compiler will respond in time). The class must contain a method called main (), the form is as follows:

Public static void main (String [] args) {

Among them, the keyword "public" means that the method can be called by the external world (Chapter 5 explained in detail). Main ()'s own argument is an array containing the String object. ARGS will not be used in this program, but you need to list this place because they saved the arguments of the command line.

The first line of the program is very interesting:

System.out.println (New Date ());

Please observe its own variable: Creating a Date object is the only purpose of being sent to Println (). Once this statement is executed, Date is no longer needed. The "garbage collector" will discover this and reclaim it when any may. In fact, we are not too big to care about the details of "Clear".

The second line calls System.getProperties (). If you look at the online user document with a web browser, you can know that getProperties () is a Static method for the System class. Since it is "static", it is not necessary to create any objects to call this method. The Static method can be used at any time whether or not there is an object of such a class. When you call getProperties (), it will generate the system properties as an object of the Properties class (Note Properties means "Properties" means). The subsequent handle is saved in a Properties handle called P. In the third line, everyone can see that the Properties object has a method called list (), which sends its entire content to the PrintStream object we passed as an argument.

The fourth and sixth lines of Main () are typical print statements. Note To print multiple string values, you can separate them with a plus sign ( ). However, you must pay attention to some strange things here. When used in the String object, the plus sign does not mean the real "add". When handling strings, we usually do not have to consider any special meaning of " ". However, Java's String class is subject to a mechanism called "operator overload". That is, the plus sign is only different from anywhere in the same way as the String object is used. For strings, it means "connecting these two strings".

But things have not ended here. Please observe the following statement:

System.out.println ("Total Memory =" rt.totalmemory ()

"Free memory ="

rt.FreeMemory ());

Where TOTALMEMORY () and FreeMemory () are returned to the value, not String objects. What happens if you "add" to a string? Like us, the compiler will also be aware of this problem, and the magic is called a method to convert the value (int, float, etc.) into a string. After this treatment, they can of course use the plus "plus" to together. This "automatic type conversion" is also divided into the "operator overload".

Many Java works are useful for "an operator overload" (one characteristic of C ). It is an example of going against it! However, this can only count the problem of compiler (program), but only for String objects. It is impossible to "overload" for any source code written by yourself.

Create a Runtime object by calling the getRuntime () method for the runtime class. The fifth line of Main () creates a Runtime object. The returned is the handle of a runtime object. Moreover, we don't have to care about it is a static object or an object created by the new command. This is because we don't have to be responsible for the clearing work, you can use the object in a large mode. As shown, Runtime can tell us about information related to memory.

2.8 Comments and embed documents

There are two types of comments in Java. The first is a conventional, C language-style annotation, inherited from C . These comments start with a "/ *", followed by comment content, and can cross multiple lines, and finally end with one "* /". Note that many programmers start with a "*" every line of continuous comment, so they often see the following:

/* this is

* A comment,

* It spans multiple lines

* /

But keep in mind that everything between / * and * / between / * and * /, so the above annotations are not different from the following:

/ * This is a comment,

It spans multiple lines * /

The second type of annotation also originated from C . This kind of comment is called "single-line comment", starting with a "//", indicating that all content of this line is comment. This type of annotation is more common because it is more convenient to write. There is no need to look for "/" on the keyboard, then look for "*" (just twice with the same key), and do not have to add an end tag at the end of the comment. The following is an example of such a comment:

// This is a single line of comments

2.8.1 Comment Document

For Java languages, the most thoughtful design is that it is not intended to write procedures for writing procedures - people also need to consider the documentation of the program. For the documentation of the program, the biggest problem is the maintenance of the document. If the document is separated from the code, then change the document each time you change the code, this will undoubtedly become a matter of quite trouble. The solution to the method seems to be very simple: the code is "link" with the document. In order to achieve this, the easiest way is to place all content in the same file. However, in order to make everything else, you must also use a special annotation syntax to mark special documents; there is also a tool to extract these comments and display it in valuable form. These are all the Java must do.

Tools used to extract annotations are called Javadoc. It uses some techniques from Java compilers to find special annotation tags we put into programs. It not only extracts information indicated by these tags, but also extracts the class name or method name of the comment. In this way, we can use the lightest workload to generate a professional program documentation. Javadoc output is an HTML file that can be viewed in your own web browser. This tool allows us to create and manage single source files and vividly generate useful documents. Because of JVADOC, we can create documents with standard methods. And because it is very convenient, we can easily get a document of all Java libraries.

2.8.2 Specific grammar

All javadoc commands can only appear in the "/ **" annotation. But the same is true, the comment ends at a "* /". Mainly in two ways, Javadoc: embedded HTML, or use "document tag". Among them, "Docu Tags" is some command starting with "@", which is placed at the beginning of the annotation line (but the preamble "*" will be ignored).

There are three types of comment documents, which correspond to elements behind comments: class, variables, or methods. That is, a class annotation is just before a class definition; the variable comment is just before the variable definition; and a method definition is just in front of a method definition. As shown in this simple example below:

/ ** A class comment * /

PUBLIC CLASS DOCTEST {

/ ** A variable comment * /

Public INT I;

/ ** A method comment * /

Public void f () {}

}

Note Javadoc can only process an comment document for public (public) and protected members. "Private" and "Friendly" (see 5 chapters) Members are ignored, we can't see any output (you can also use the -Private tag including private members). This is reasonable because only public and protected members can be used outside of the file, which is the hope of the customer programmer. However, all class comments will contain it in the output.

The output of the above code is an HTML file that has the same standard format as other Java documents. Therefore, users will be familiar with this format, which can be easily "roaming" in the class you designed. When designing the program, be sure to consider entering the above code, with Javadoc to process, how to watch the final HTML file.

2.8.3 embed HTML

Javadoc passes the HTML command to the final generated HTML document. This allows us to make full use of huge power of HTML. Of course, our final motivation is formatting code, not for demosol. One example is listed below:

/ **

*

* System.out.println (New Date ());

*

* /

It can also be used to use HTML as in other web documents, format the ordinary text, make it more organized, more beautiful:

/ **

* You or even can insert a list:

*

*

  • project one

    *

  • project two

    *

  • project three

    *

    * /

    Note that in the document comments, the most beginning of the one-line will be discarded by Javadoc. There is also a leading space at the same time. Javadoc formats all content to match the standard document appearance. Do not use the title of

    or
    as embedded HTML, because Javadoc will insert your own title, and we give the title with it. All types of comments documents - class, variables, and methods - support embedded HTML.

    2.8.4 @see: Reference other classes

    All three types of comments documents can include @see tags that allow us to reference documents in other classes. For this tag, Javadoc generates the corresponding HTML and links it to another document. The format is as follows:

    @see class name

    @see full class name

    @see Complete Class # method name

    Each format will automatically join a hyperlink "See Also" entry in the generated document. Note that Javadoc does not check the hyperlink we specified, and does not verify that they are valid.

    2.8.5 class document tag

    The class document can also include tags for version information and author names. Class documents can also be used for "interface" purposes (explained later later).

    @Version

    The format is as follows:

    @version version information

    Among them, "Version Information" represents any suitable information as version description. If the "-Version" tag is used in the Javadoc command line, the publication information will be extracted from the generated HTML document.

    2. @Author

    The format is as follows:

    @Author Author Information

    Among them, "author information" includes your name, electronic letter address, or any other suitable information. If the "-author" tag is used in the Javadoc command line, the author information is extracted specifically from the generated HTML document.

    Multiple such tags can be used for a series of authors, but they must be placed continuously. All author information will be deposited in a single paragraph of the final HTML code.

    2.8.6 Variable Document Tag

    Variable documents can only include embedded HTMLs and @see references.

    2.8.7 Method Document Tag

    In addition to embed HTML and @see references, the method also allows document tags for parameters, return values, and violations.

    @Param

    The format is as follows:

    @Param parameter name

    Where "Parameter" is an identifier within the parameter list, and the "description" represents some instructions that can continue to subsequent lines. Once a new document mark is encountered, it is considered that the previous description ends. Any number of instructions can be used, each parameter.

    2. @Return

    The format is as follows:

    @Return

    Wherein, "Description" means the meaning of the return value. It continues to the back of the line.

    3. @Exception

    We will tell in Chapter 9 about "Exception". Briefly, they are some special objects. If a method fails, they can "throw" objects. When calling a method, although only one violation object appears, some special methods may produce any number, different types of violations. All of these violations need to be explained. Therefore, the format of the violation marker is as follows:

    @Exception full class description

    Among them, the "full class name" explicitly specifies the name of a violation class, which is defined in other places. "Description" (also continued to the following line) tells us why this special type of violation will appear in the method call.

    4. @DepRecated

    This is a new feature of Java 1.1. This tag is used to indicate that some old function has been replaced by improved new features. The role of this tag is that users do not have to use a specific function, because this function may be abandoned when the future is revised. If a method is marked as @DepRecated, a warning for the compiler will be received when using this method. 2.8.8 Document Example

    Below is our first Java program, but has added a complete document comment:

    92Player

    first row:

    //: Property.java

    Using my own way: Take a ":" as a special mark, pointing out that this is a note containing the name of the source file. The last row also ends with such a comment, which marks the end of the source code list. In this way, the code can be easily extracted from the body of this book and check it with a compiler. The details in this regard are in Chapter 17.

    2.9 Code Style

    An informal Java programming criterion is a capitalization of a class name. If the class is constructed by several words, then they close together (that is, do not use the underline to separate the name). In addition, each letter of each embedded word is in uppercase. E.g:

    Class allThecolorsoftheRainBow {// ...}

    For other almost all content: method, field (member variable), and object handle name, acceptable style is similar to class style, but the first letter of identifier is lowercase. E.g:

    Class allThecolorsoftHerainBow {

    Int AnintegerRepresentingColors;

    Void Changethehueofthecolor (int newhue) {

    // ...

    }

    // ...

    }

    Of course, pay attention to the user must type all of these long names and cannot be lost.

    2.10 Summary

    Through this chapter, everyone has already contacted enough Java programming knowledge and knows how to write a simple program. In addition, the overall situation of language and some basic ideas have a certain degree of understanding. However, all examples of this chapter are single-line form "Do this, then do that, then do some things". If you want the program to make a choice, what should I design? For example, "If this is the result of this is red, then do it; if not, do some things." For this basic programming method, the next chapter will explain how Java is implemented in Java.

    2.11 practice

    (1) Refer to the first example of this chapter, create a "Hello, World" program, simply displaying this sentence on the screen. Note It only needs one method in your own class ("main" method to execute when the program starts). Remember to set it to static form and place an argument list - even if you don't use this list at all. Compile this program with Javac and run it with Java.

    (2) Write a program to print three arguments from the command line.

    (3) Find the second version of the Property.java, which is a simple comment document example. Please perform Javadoc on your file and watch the results in your own web browser.

    (4) Based on the procedure of practice (1), the comment document is added to it. With Javadoc, extract this comment document as an HTML file and watch it with a web browser.

  • 转载请注明原文地址:https://www.9cbs.com/read-4718.html

    New Post(0)