Thinking in Java 20

zhaozj2021-02-11  212

Appendix B Contrast C and Java

"As a C programmer, we have already mastered the basic concepts of object-oriented programming, and Java's syntax is undoubtedly very familiar. In fact, Java is originally derived from C ."

However, there are still some significant differences between C and Java. It can be said that these differences represent great progress in technology. Once we figure out these differences, we will understand why Java is an excellent programming language. This appendix will guide you to understand some of the important features of Java and C .

(1) The biggest obstacle is that the speed of the Java is about 20 times slower than the execution speed of C. No matter what you can't prevent Java language from compiling. When writing this book, some quadruple compilers have just appeared, they can significantly speed up. Of course, we have a complete reason to think that there is a purely compiler suitable for more popular platforms, but if there is no compiler, due to speed limits, some problems must be Java can't be solved.

(2) Like C , Java also provides two types of annotations.

(3) All things must be placed into a class. There is no global function or global data. If you want to get the feature with the global function, consider placing the Static method and STATIC data into a class. Pay attention to things that are not like structures, enumerations, or joint this category, everything is only "class"!

(4) All methods are defined in the subject of the class. So in the eyes of C , it seems that all functions have been embedded, but the truth is not how the embedded problem is described later).

(5) In Java, class definitions take the same form as C . But there is no semicolon that is ended. There is no class declaration in the form of Class Foo, only class definitions.

Class atype ()

Void amethod () {/ * method main body * /}

}

(6) There is no scope operator "::" in Java. Java uses the point to do all things, but you can use it without considering it because you can only define elements in a class. Even if those methods are defined, they must also be inside a class, so there is no need to specify the scope of the scope. One difference we noticed is the call to the Static method: use classname.methodname (). In addition to this, the name of the package is established with the point number and can use the import keyword to implement a part of the "#include" of C ". For example, the statement below:

Import java.awt. *;

(#Include is not directly mapped into IMPORT, but there is a similar feeling in use.)

(7) Similar to C , Java contains a series of "primitive type" to achieve more efficient access. In Java, these types include Boolean, Char, Byte, Short, Int, Long, Float, and Double. The size of all major types is inherent, and the specific machine is not related to the specific machine (taking into account the problem of transplantation). This will definitely have a certain impact on performance, depending on the different machines. Type checks and requirements becomes more demanding in Java. E.g:

■ Conditional expressions can only be the Boolean (Boolean) type, and an integer cannot be used.

■ The result of an expression like X Y must be used; "side effects" cannot be implemented using only "x y".

(8) CHAR (character) type uses internationally universal 16-bit Unicode character set, so you can automatically express characters in most countries. (9) Static references will automatically convert to String objects. Unlike C and C , there is no independent static character array string available.

(10) Java adds three right shift operators ">>>", with a function similar to the "logical" right shift operator, which can be inserted into the zero value at the end tail. ">>" will insert a symbol bit (ie "arithmetic" shift while shifting.

(11) Although the surface is similar, the Java array is a quite structure in the Java array compared to C , and has a unique behavior. There is a read-only Length member, which can know how much array can be known. And once the array boundary is exceeded, the running period will automatically discard an exception. All arrays are created in memory "Heap", and we can assign an array to another (just simply copy the array handle). The array identifier belongs to the first level object, and all of its methods are usually applicable to all other objects.

(12) For all objects that are not a primary type, they can only be created via the new command. Unlike C , Java has no corresponding commands "on the stack" to create objects that are not the primary type. All main types can only be created on the stack, and do not use the new command. All major classes have their own "package (gear)" class, so you can create equivalents based on NEW, with memory "stack" (primary type array is an exception: they can initialize in C Perform allocation, or use new).

(13) There is no need to perform early statement in Java. If you want to use a class or method before defining, just use it directly - the compiler will guarantee the proper definition. So and differ in C , we will not encounter any questions involved in advance.

(14) Java has no pre-processing machine. If you want to use another library, just use the import command and specify the library name. There is no macro similar to the pretreatment machine.

(15) Java replaces the namespace with a package. Since all things are placed in a class, and because of a mechanism called "Package", it can make an operation similar to namespace decomposition for class names, so the problem that naming is no longer entering our consideration. . The data package also collects the components of the library at a single library name. We only need to simply "import" a package, and the remaining work will be automatically completed by the compiler.

(16) The object handle defined as a member will automatically initialize NULL. The initialization of basic class data is reliable in Java. If initialization is not explicit, they get a default value (zero or equivalent value). They can be explicitly initialized (explicit initialization): Either define them within the class or defined in the builder. The syntax used by the syntax is more easily understood than the syntax of C , and it is fixed to Static and non-StATIC members. We don't have to define Static members from the outside, which is different from C .

(17) In Java, there is no pointer like C and C . When you create an object with NEW, you will get a reference (this book is called "handle"). E.g:

String s = new string ("howdy");

However, C references must be initialized during creation, and it is unable to define a different location. But Java references are not necessarily limited to the location of creation. They can be arbitrarily defined according to the situation, which eliminates part of the needs of the pointer. Another reason for a large number of pointers in C and C is to point to any of the memory locations (this will make them unsafe, and the reason for Java does not provide this support). The pointer is often seen as an effective means of moving around the basic variable array. Java allows us to achieve the same goal in a safer form. The ultimate method of solving the pointer problem is "inherent methods" (discussed in Appendix A). When the pointer is passed to the method, it usually does not bring too much problem because there is no global function at this time, only classes. And we can pass reference to the object. The Java language is the most beginning to claim that "completely does not adopt a pointer!" But with many programmers question how to work? So later, "adopts a restricted pointer". Everyone can judge whether it is "true" is a pointer. But no matter what case, there is no pointer "arithmetic". (18) Java provides a "constructor" similar to C . If you don't define one yourself, you will get a default builder. And if you define a non-default builder, you won't automatically define the default builder for us. This is the same as C . Note that there is no replication builder because all own variables are passed by reference.

(19) There is no "destructor" in Java. Variables do not have a "scope" problem. "Presence time" of an object is determined by the existence time of the object, is not determined by the garbage collector. There is a Finalize () method is a member of each class, which is similar to the "destroyer" of C . But finalize () is called by the garbage collector, and is only responsible for the release of "resource" (such as open files, sockets, ports, URLs, etc.). If you need to do something in a specific location, you must create a special method and call it and you can't rely on Finalize (). On the other hand, all objects in C will be destroyed (or "should"), but all objects in Java will be treated as "garbage". Since Java does not support the concept of destroyer, a clear method must be created carefully when necessary. And for the basic class and members objects within the class, you need to clearly call all clear methods.

(20) Java has a method "overload" mechanism, and its working principle is almost identical to the overload of the C function.

(21) Java does not support the default argument.

(22) No goto in Java. The unconditional jump mechanism it takes is "Break Tag" or "Continue Standard" for jumps out of the current multi-nest loop.

(23) Java uses a single grading structure, so all objects are uniformly inherited from the root OBJECT. In C , we can launch a new inheritance tree anywhere, so finally, I often see "a forest" containing a lot of trees. In Java, we have only one grading structure in anyway. Although this surface seems to have caused restrictions, since we know that each object must have at least an Object interface, it is often more powerful. C currently seems to be the only OO language that does not have a single structure.

(24) Java does not have other forms of template or parameterization type. It provides a collection of collections: Vector, Stack, and Hashtable (have been used to accommodate Object references. Using these collections, our series of requirements can be met. However, these collections are not designed for fast calls such as C Standard Template Library (STL). The new collection in Java 1.2 is more complete, but still does not have the high efficiency means such as the authentic template. (25) "Garbage Collection" means that the memory vulnerability in Java will be much less, but it is not completely impossible (if an inherent method for allocating storage space is called, the garbage collector cannot track it. Monitoring). However, memory vulnerabilities and resource vulnerabilities are mostly caused by improper Finalize () or due to the release of a resource ("destroyer" at this time). The garbage collector is a great progress based on C , making many programming problems in invisible. However, there is no problem with a few garbage collectors, but it is not very suitable. However, the large amount of garbage collector also makes this disadvantage.

(26) Java built a support for multi-threaded. With a special Thread class, we can create a new thread by inheritance (abandon the Run () method). If you use the Synchronized keyword as a type limiter of the method, the mutual exclusion phenomenon will occur at the level of the object. At any given time, there is only one thread to use an object's synchronized method. On the other hand, after an Synchronized method enters, it will first "lock" objects to prevent any other synchronized method from using that object. Only the object will be "unlocked" only to exit this method. Between threads, we still have to be responsible for achieving more complex synchronization mechanisms, making your own "monitor" class. The recursive synchronized method can work normally. If the priority level of the thread is the same, the "fragmentation" of time cannot be guaranteed.

(27) We are not like controlling code blocks like C , but to place access qualifiers (public, private, and protected) into the definition of each class member. If a "explicit" (clear) definition is not specified, it will default to "Friendly". This means that other elements in the same package can also be accessed (equivalent to "Friends" - friends they become C , but they cannot be accessed by any element outside the package. Class - and each method in the class - has an access qualifier that determines if it can "visible" outside the file. Private keywords are usually very useful in Java because "Friendly" access is usually more useful than access to other classes in the same package. However, in multi-threaded environments, it is very important to use Private. Java's protected keyword means "can be accessed by the successor, or can be accessed by other elements in the package." Note that Java does not have an element with the C protected keyword equivalent, the latter means "can only be accessed by the successor" (previously available "Private Protected" to achieve this, but the combination of keywords has been canceled) .

(28) Nested class. In C , nested the class helps hide the name and facilitate the organization of the code (but C "namespace" has enabled the name of the name. Java's "package" or "package" concept is equivalent to C namespace, so it is no longer a problem. Java 1.1 introduces the concept of "internal classes", which secretly keeps a handle to the external class - need to use during the creation of internal class objects. This means that internal objects may access members of the external class, do not require any conditions - just like those members directly affiliated to internal class objects. This provides a better solution for callback issues - C is solved with a pointer to a member. (29) Due to the inner class presenting, there is no pointer to the member in Java.

(30) Java does not exist "embedded" method. The Java compiler may decide on a way, but we have no more control power. In Java, you can use the final key to use the FINAL keyword to "recommend" for embedding operations. However, embedded functions are only a suggestion for the C compiler.

(31) Inheritance in Java has the same effect as C , but the syntax used is different. Java uses the extends keyword flag from a basic class's inheritance, and uses the Super key to point out the method prepared in the basic class, which has the same name as our current method (however, the Super key in Java only allows us Method of accessing the parent class - the last level of the hierarchical structure). By setting the basic class of the basic class in C , we can access the method of deeper the hierarchical structure. The underlying class builder can also be called with the Super Keyword. As early as possible, all classes will eventually inherit from Object. Unlike C , there is no clear builder initialization list. However, the compiler will force us to initialize all of the base classes at the beginning of the builder body, and we do not allow us to do this behind the main body. By combining automatic initialization and abnormality from unmected object handles, the initialization of members can be effectively guaranteed.

1045 page

(32) Inheritance in Java does not change the level of protection of basic members. We cannot specify public, private, or protected in Java, which is the same as C . In addition, priority methods in derived classes cannot reduce access to basic methods. For example, suppose a member belongs to public in the base class, and we use another method instead of it, the method for replacement must also belong to public (the compiler will check).

(33) Java provides an interface keyword, which is an equivalent to create an abstract base class. Fill the abstract method and no data member. In this way, there is a significant difference between the two to extensions only designed as an interface. It is not worth using the Abstract keyword to produce a similar effect because we cannot create an object belonging to that class. A Abstract (Abstract) class can contain abstract methods (although not required in it), it can also include code for specific implementation. Therefore, it is limited to a single inheritance. This solution avoids the needs of some mechanisms similar to the C virtual basis.

To create a version of an interface (ie, create an instance), you need to use the imports keyword. Its syntax is similar to inherited grammar, as shown below: 1046 Page Program

(34) There is no Virtual keyword in Java because all non-Static methods will definitely use dynamic binding. In Java, programmers do not have to decide whether to use dynamic binding. The reason why C uses Virtual because we can omit the performance of performance, thereby obtaining a small amount of improvement in performing efficiency (or in other words: "If not, there is no need to pay for it"). "). Virtual will often cause a certain degree of confusion and get unpleasant results. Final keyword specifies some ranges for performance - it points to the compiler that this method cannot be replaced, so its range may be static (and be embedded, so using C non-Virtual calls) . These optimization work is done by the compiler.

(35) Java does not provide multiple inheritance mechanisms (MI), at least not as C . Similar to protected, the MI surface is a very good idea, but only if you really face a specific design problem, you need it. Since Java uses a "single" grading structure, only MI is required only in very few occasions. The Interface Keyword will help us complete the merger of multiple interfaces.

(36) The type identification function of the runtime is very similar to C . For example, in order to obtain information related to the handle X, you can use the following code:

X.getClass (). Getname ();

For a "type security" tightening, you can use:

Derived D = (Derived) Base;

This is the same as the old style C shape. The compiler will automatically call dynamic styling mechanisms without requiring additional syntax. Although it is not like the advantages of the C "New Casts", Java will check the usage and discard those "exceptions", so it does not allow bad styles like C .

(37) Java has taken different abnormal control mechanisms because there is no constructor. You can add a Finally clause to force a specific statement to make the necessary clearing. All exceptions in Java are inherited from the basic class throwable, so we can ensure that we get a general interface.

1047 program

(38) The exception specification of Java is much better than C . After discarding an error, it is not called a function during operation as C , and the Java exception specification is checked and executed during compilation. In addition, the substituted method must comply with the exception specification of the basic class version of the method: they can discard the specified exception or other exceptions derived from those exceptions. In this way, we finally got a more "robust" exception control code.

(39) Java has the ability to overload, but not allowed to overload. The String class cannot connect different strings with and = operators, and String expressions use automatic type conversion, but that is a special internal construction.

(40) Through the prior convention, the constrapers that often appear in C have been controlled in Java. We can only pass the handle of the object, and the local copy will never be automatically generated for us. If you want to use a technique similar to C to transfer, Clone () can be called to generate a local copy of the variable (although Clone () is still still rough - see Chapter 12). There is no copy buffer that is automatically called. In order to create a constant value of a compile period, you can be encoded below: Static Final Int size = 255

Static Final Int Bsize = 8 * size

(41) A significant difference between the "application" programming and the programming programming is significant difference due to safety. One of the most obvious issues is that the film does not allow us to write a disk, because this will cause the program that is downloaded from the remote site, unknown programs may change our disk. This situation has changed as Java 1.1 is a reference to digital signature technology. Depending on the digital signature, we know all the author of a program, and verify that they have been authorized. Java 1.2 will further enhance the ability of the program.

(42) Since Java may limit much in certain occasions, sometimes it is sometimes unwilling to use it to perform important tasks such as directly accessing hardware. Java solves this problem with the "inherent way", allowing us to call functions written by other languages ​​(currently C and C ). In this way, we must solve problems associated with the platform (using a non-portable form, but those code will then be isolated). The package cannot call the inherent method, only the application can be.

(43) Java provides built-in support for the comment document, so the source code file can also contain their own documentation. Through a separate program, these document information can be extracted and resched into HTML. This is undoubtedly a great progress of document management and application.

(44) Java contains some standard libraries for completing specific tasks. C relies on some non-standard, by other vendors. These tasks include (or shortly):

■ connected network

■ Database connection (via JDBC)

■ Multi-threaded

■ Distributed objects (via RMI and CORBA)

■ Compression

■ Trading

Since these libraries are easy to use, and it is very standard, it can greatly speed up the development speed of the application.

(45) Java 1.1 includes Java Beans standards, which can create components used in a visual programming environment. Due to the same criteria, the visual component can be used in all manufacturers' development environments. Since we don't rely on a vendor's scheme to design a visual component, the selection of components will increase, and the performance of the component can be improved. In addition, Java Beans is designed to be very simple and facilitated programmers; and those specialized component frameworks developed by different manufacturers require more in-depth learning.

(46) If the access Java handle fails, it will discard an exception. This discard test does not have to do just before using a handle. According to Java design specifications, it is only necessary to discard in some form. Many C runtime systems can also discard those exceptions caused by pointer errors.

(47) Java is usually more robust, and the means taken here is as follows:

■ Object handle is initialized into NULL (a keyword)

■ The handle will definitely be checked and discarded at an error.

■ All array access will be checked, timely discover border violations

■ Automatic garbage collection to prevent memory vulnerabilities

■ Clearly, "fool type" exception control mechanism

■ Provide simple language support for multithreading

■ Field code code checking network blocks

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

New Post(0)