Contrast C ++ and Java

Original link: http://www.cnblogs.com/binterminator/articles/1579028.html
Comparing C ++ and Java
source: java programming ideas)

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

However, there are still some significant differences between C ++ and Java. It can be said that these differences represent a great technological progress. Once we figured out these differences, they will understand why Java is an excellent programming language. This appendix will guide you to know some important characteristics that distinguish Java and C ++.

(1) The biggest obstacle is the speed: speed of execution of Java than C explained on about 20 times slower. Whatever can stop the Java language compiler. The time of writing, just there are some quasi-real-time compiler, which can significantly speed up. Of course, we have every reason to believe that there will be more suitable for popular platform of pure inherent compiler, but if not those compilers, due to the speed limit, some questions must be Bunengjiejue of Java.

(2) and, like C ++, Java also provides two types of comments.

(3) All things must be placed in a category. Global function or global data does not exist. To obtain the global function equivalent functions may be considered static methods and data into a static class. Note that no like structure, or a combination of enumeration such things, all only "class" (Class)!

Defined body (4) of all the methods in the class. So in C ++ perspective, it seems that all functions are embedded, but that's not the how (embedded problems described in later).

(5) In Java, the class definition and C ++ to take almost the same form. But did not mark the end of a semicolon. No class foo class declaration in this form, only the class definition.

aType class ()

void aMethod () {/ * Method body * /}

}

(. 6) is not the Java operator of scope "::." Java using the dot do everything, but can not consider it, because you can only define the elements in a class. Even those definitions must also be within a class, so there is no need to specify the range of scope. We note one difference is that the call to the static method: Use ClassName.methodName (). In addition, package (package) name is established by a dot, and can be part of "#include" function import realize C ++ keywords. For example, the following statement:

Import the java.awt *;.

(#Include not directly mapped to import, but there is a similar feeling when in use.)

(7) and is similar to C ++, Java contains a series of "main types" (Primitive type ), in order to achieve a more efficient access. In Java, these types include boolean, char, byte, short, int, long, float and double. All the main types of size are inherent and independent of the particular machine (migration issues into consideration). This performance will certainly be some impact, depending on different machines. Type of inspection and requirements become more demanding in Java. For example:

■ conditional expression can only be boolean (Boolean) type, do not use integers.

■ results must be used such as an expression X + Y; not simply with "X + Y" to achieve the "side effects."

(8) char (character) type using the internationally accepted 16-bit Unicode character set, it can automatically express the character of most countries .

(9) static reference strings are automatically converted into String objects . And C and C ++ different, there is no independent static character array string available.

(10) Java adds three right shift operator ">>>", having a "logical" right shift operator similar function, may be inserted at the end of zero value most. ">>" will be inserted at the same time shifting the sign bit (i.e., "Arithmetic" shift).

(11) Although a similar upper surface, compared with C ++, Java array uses a quite different structure, and having a unique behavior. There are members of a length read-only , which allows you to know how much the array. And more than once the array bounds, runtime checking automatically discard an exception. All arrays are in memory "heap" was created, we can assign an array to another (simply copy the array handle). An array of identifiers that are first-class objects, that all the methods are generally applicable to all other objects.

(12) For all objects that do not belong to the main types can only be created through the new command. Unlike C ++, Java is no corresponding command creates the main type of object does not belong "on the stack." All the main types can only be created on the stack, without using the new command . All major classes has its own "package ()" in class, can be created by the new new equivalent, to memory "heap" object-based (array of primitives are an exception: they may be set as C ++ as initialized by allocation, or using new).

(13) the Java does not have to be declared in advance . To use a class or method as defined above, directly using it to - the compiler used to ensure proper definition. So different in C ++, we will not run into any problems involving early references.

(14) the Java machine without pretreatment . If you want to use another library class, simply use the import command and specify the library name. Similar to the macro preprocessor does not exist.

(15) the Java package instead of using namespaces . Because everything will be placed in a class, but thanks to a mechanism called "package", it can be similar to the namespace decomposition of operations for the class name, so the question is no longer enter the name of the column our consideration . Packet assembly will be collected in a single library name library. We simply "import" (import) a pack, the remaining work will be done automatically by the compiler.

(16) is defined as a member of the class object handle is automatically initialized to null . Initialization of the base class data members has been a reliable guarantee in Java. Unless explicitly initialized, they will obtain a default value (or the equivalent value of zero). They can be explicitly initialized (explicit initialization): either they are defined in the class, or defined in the builder. The syntax is easier to understand than C ++ syntax, but also for static and non-static members for both fixed. We do not have external storage from the definition of static members, which are different and C ++.

(17) in Java, C and C ++ do not like that kind of pointer. Create an object with a new time, you get a quote (the book has been referred to as "handle") . For example:

String = S new new String ( "Howdy");

however, C ++ reference must be initialized when it is created and can not be redefined to a different location . But Java reference position is not necessarily limited to create. They can be based on arbitrary definitions , which would eliminate the need for some pointers . Another reason for the extensive use of pointers in C and C ++ in order to be able to point to any memory location (This also makes the reason they become unsafe, but also Java does not provide this support). Pointer is usually regarded as an effective means of substantially moved about in a variable array. Java allows us to more secure form to achieve the same goal. The ultimate solution to the problem pointer is "intrinsic method" (discussed in Appendix A). When passing a pointer to the method usually it does not bring much of a problem, because at this time there is no global functions, only classes. And we can pass a reference to the object . Java language initially stated that he "absolutely does not use the pointer!" But as many programmers do not have to question how pointers work? Then later statement "using the pointer is limited." We can judge for themselves whether it is "true" is a pointer. But no matter under what circumstances, there is no pointer "arithmetic."

(18) Java and C ++ provides a similar "builder" (Constructor). If you do not own a defined, you'll get a default constructor. And if the definition of a non-default constructor, it will not automatically define a default constructor for us. This and C ++ are the same. Note that no copy constructor, because all arguments are passed by reference.

(19) Java does not "damage control" (Destructor). Variables "Scope" does not exist . "There is a time" of an object is determined by the presence of the target time is not determined by the garbage collector. There finalize () method is a member of every class, which is somewhat similar to the C ++ "breaker." But finalize () is called by the garbage collector, and is only responsible for the release of "resources" (such as open files, sockets, port, URL, etc.). To do a certain kind of thing in a particular place, you must create a special method, and call it, can not rely on finalize (). On the other hand, all the objects in C ++ will (or "should") damage, but not all objects in Java are treated as "junk" collected. due to Java does not support the concept of damage control, so when necessary, care must be taken to create a cleanup method . And for the base class and member objects in the class, you need to explicitly call all removal methods.

(20) Java has the method "overload" mechanism, which works with C ++ function overloading is almost identical.

(21) Java does not support default arguments.

(22) Java is not goto. It unconditional jump mechanism takes the "break tag" or "continue standard" for the current out of multiple nested loops.

(23) the Java uses a single radical hierarchical structure , so all objects are inherited from the root class Object unity of . In C ++, we can start a new inheritance tree anywhere, so in the end tend to see the tree contains a large number of "a forest" . In Java, in any case we have only one hierarchy . Although the surface seems to have caused this limit, but because we know that every object must have at least one Object interface, you can often get more powerful capabilities. C ++ does not currently seem to be the only compulsory single structure the only OO language.

(24-) the Java no other form template or parameterized types . It provides a series of collection: Vector (Vector), Stack (Stack), and Hashtable (hash table) for receiving Object references . With these collections, our set of requirements can be satisfied. But these collections are not like C ++ to achieve quick call as "Standard Template Library" (STL) and design. The new set of Java 1.2 is even more complete, but still have high efficiency as authentic template means.

Case (25) "garbage collection" means the emergence of memory leaks in Java will be much less, but it is not impossible ( if calling a native method for allocating storage space, the garbage collector can not be tracked monitor ). However, memory leaks and resource vulnerability is due to improper preparation finalize () caused by , or due to the release of a resource at the end of a block allocated due ( "destroyer" is particularly convenient at this point). The garbage collector is a great advance in C ++ on the basis of so many programming problems diminish in the invisible. But there is a question of a few incompetent garbage collector power, it is not suitable. But a number of advantages garbage collector makes the disadvantages of the pales.

(26) the Java built-in support for multithreading. Use a special Thread class, we can create a new thread through inheritance (to give up the run () method) . If synchronized (synchronous) keyword as a method of using a type qualifier, mutually exclusive phenomenon which occurs in the object level. At any given time, only one thread can use synchronized method of an object . On the other hand, after entering a synchronized method, it first "locked" objects, to prevent any other synchronized method and then use that object. Only quit this method, the object will be "unlocked." Between threads, we are still responsible for implementing more complex synchronization mechanism, is to create your own "Monitor" category. Synchronized method recursive function normally. If the same priority thread, the time of "slicing" can not be guaranteed.

(27) We did not like C ++ control statement block of code, but the access modifier (public, private and protected) into the definition of each class member's. If you do not specify a "explicit" (explicit) qualifier, it will default to "friendly" (Friendly ). This means that other elements in the same package can access it (they have become the equivalent of C ++ "friends" - friends), but can not be accessed by any element outside of the package. Class - and each method in the class - have access to a qualifier to determine whether it can be "visible" in an external file. private key is usually little use in Java , as compared with the same exclusive access to other classes within a package, "friendly" visit is usually more useful. However, in a multi-threaded environment, proper use of private is very important . The Java protected keyword means "can be accessed successor, or by the other elements in the package access." Note that Java does not have the elements of C ++ protected keyword equivalent , which means "can only be accessed by the successor" (previously available "private protected" for this purpose, but this has been canceled combination of keywords) .

(28) nested class. In C ++, nesting helps hide the class name, and to facilitate the organization of the code (C ++, but the "namespace" is the name of the hidden superfluous). Java "pack" or "pack" is equivalent to the concept of C ++ namespace , It is no longer a problem. Java 1.1 introduced the concept of "inner class", which is the secret to keep a handle to the outer class - to create an internal class object to use when needed. This means that the object inside the class members may be able to access external class object, no need any condition - as if those members directly under the inner class object. This provides a better solution --C ++ callback problem is solved pointer to member.

(29) Because of the kind of inner classes described earlier, Java so there are no pointers to members.

(30) Java absent "embedded" (inline) method. Java compiler might embed a method to decide, but we have no more control power. In Java, it can be used as a method of final keyword , so that "recommended" for embedding. However, embedding function for the C ++ compiler is also only a suggestion.

(31) Java inheritance in C ++ has the same effect, but the syntax is different. Java extends keyword with a sign from inheriting from a base class, and pointed out ready to call the method in the base class with a super keyword that has the same name and the way we currently resides (However, the super keyword in Java only allows us the method of accessing the parent class - i.e. the one hierarchy). By setting the scope of the base class in C ++, we can hierarchy deeper way to access is located. You can also call the base class constructor using the super keyword. As noted earlier, all final class are automatically inherited from Object years. Unlike C ++, explicit constructor initialization list does not exist. But the compiler forces you to do all the basic class initialization at the beginning of construction of the body, and not allow us to carry out this work in the back part of the body. By using a combination of automatic initialization and the initialization from uninitialized object handle exceptions, members can be effectively guaranteed.

1045 program

(32) Java Inheritance does not change the protection level of the base class members. We can not be specified in Java public, private or protected inheritance, unlike C ++ are the same. In addition, the preferred method in the derived class can not be reduced to the base class method access. For example, assume a member belonging to the base class public, we replaced it with another method, the method used for replacement must also belong to the public (the compiler will automatically check).

(33) Java provides an interface keyword, its role is to create an equivalent abstract base class. Abstract method filled therein, and no data members. Thus, an interface designed for only thing, and by the extends keyword to extend the existing functionality basis, between the two will produce a significant difference. Not worth it with the abstract keyword to produce a similar effect, because we can not create an object belonging to that class. An abstract (Abstract) abstract class may include a method (Although not required in what it contains), it can also contain the code for a particular implementation. Therefore, it is limited to a single inheritance. By combination with the interface, the program avoids the need for some mechanism similar to C ++ as a virtual base class of.

Can be created as "exemplary" (i.e., creates an instance of) a version of the interface (interface), the need to use implements keyword. Its syntax is similar to inheritance syntax is as follows:

1046 program

(34) Java virtual keyword is not, because all non-static methods will certainly use dynamic binding. In Java, the programmer does not have to decide whether to use dynamic binding. The reason why C ++ uses the virtual, is because we adjust the performance, by its omission to obtain a small amount to enhance the efficiency of (or in other words: "If you do not, there is no need to pay for it"). virtual often confusing to some extent, but the results obtained unpleasant. The final keyword to adjust the performance of a predetermined number of range - it noted that this method can not be substituted by the compiler, so it may be static range constraint (and become embedded state, using the C ++ equivalents of a non-virtual call) . These optimizations work is done by the compiler.

(35) Java does not provide multiple inheritance (MI), at least we do not do that as C ++. And protected Similarly, the MI surface is a very good idea, but only when the real face of a specific design problems before they know they need it. Because Java uses a "single" hierarchical structure, it is only in rare cases they are MI. interface keywords will help us work automatically merge multiple interfaces.

(36) run to identify the type of function is very similar to C ++. For example, to obtain information related to handle X, using the following codes:

x.getClass () getName ();.

For a "type-safe" tightening shape, may be used:

derived D = (derived) Base;

this and old-style C shape is the same. The compiler automatically calls the dynamic modeling mechanism, does not require the use of additional syntax. Although it does not like the C ++ "new casts" that has the advantage of being easily locate modeling, but Java will check usage, and discard those "abnormal", so it's not like C ++ that allows bad shape existence.

(37) Java exception take a different control mechanisms, because the builder does not exist. You can finally add a clause to enforce a particular statement for any necessary cleanup work. All Java exceptions are inherited from the base class Throwable comes in, it is possible to ensure that we get a common interface.

1047 program

(38) is much more excellent than the Java exception specifications in C ++. After discarding a wrong exception, not like C ++ as a function is called during the run, Java exception specifications are checked and executed during compilation. In addition, the method must comply with the substituted base class version of the method of that specification exception: they can be discarded from the specified exception or other abnormal derived from those exceptions. As a result, we end up with more "robust" abnormal control code.

(39) Java with the capacity overload, but does not allow operator overloading. String class can not + + = operator and connected to different string String expression and use of an automatic type conversions, but it is a special case of built.

(40) by prior agreement, C ++ const problems that often appear in Java has been brought under control. We can only pass a handle to an object, a local copy will never be automatically generated for us. If you wish to use something like C ++ passed by value like technology, you can call clone (), creates a local copy of the argument (although the clone () the design is still rough is still significant - see Chapter 12). Simply copy is automatically called does not exist builder. To create a compile-time constant value, this may be encoded as the following:

static int SIZE = 255 Final

static int Final BSIZE. 8 * SIZE =

(41) For security reasons, there is a significant difference between the programming and the programming "application" and "program film". One of the most obvious problem is that the applet does not allow us to write to the disk, because doing so would cause downloaded from remote sites by unknown programs may casually rewrite our disk. With reference to the Java 1.1 digital signature technology, this situation has changed. The digital signature, we can know exactly how all of the pieces of a program, and verify that they have been authorized. Java 1.2 will further enhance the ability of the program sheet.

(42) Due to Java in some cases may seem too restrictive, so sometimes reluctant to use it to perform important tasks such as direct access to hardware. Java solution to this problem is to "intrinsic method" allows us to call functions written in other languages by the (currently only supports C and C ++). As a result, we will surely be able to solve the problem of platform-dependent (in the form of a non-portable, but that code will then be quarantined). Applet can not call native methods, only the application can.

(43) Java provides built-in support for annotation of the document, so the source code files can also contain their own documentation. By a separate program, which document information can be extracted and re-formatted into HTML. This is undoubtedly a great progress and document management applications.

(44) Java contains some standard library for a particular task. C ++ rely on a number of non-standard libraries provided by other vendors. These tasks include (or will soon include):

■ networking

■ Database Connectivity (via JDBC)

■ Multithreading

■ distributed objects (via RMI and CORBA)

■ compression

■ Trading

Because these libraries easy to use, and very standard, so can greatly accelerate the development of applications.

(45) Java 1.1 Java Beans contain standard components which can be used to create in a visual programming environment. Due to abide by the same standard, so the visual component can be used in all vendor development environment. Since we do not rely on a single vendor solution for design visualization components, so the choice of components will increase, and improve the effectiveness of the assembly. In addition, Java Beans design is very simple, easy to understand programmer; and those dedicated component framework developed by different vendors require more in-depth study.

(46) If Java handles access fails, it will be discarded once an exception. This does not have to just discard the test carried out before using a handle. According to the design specifications of Java, but said exceptions must be discarded in some form. Many C ++ runtime system can discard those exceptions due to the pointer error.

(47) Java is usually much more robust means to this end taken are as follows:

■ object handle initialized to null (a keyword)

■ handle will certainly be checked and discarded when an error occurs abnormal

■ All array accesses are checked in a timely manner found that boundary violations cases

■ automatic garbage collection, to prevent memory leaks

■ clear, "fool" type of exception control mechanism

■ provides simple language support for multi-threading

■ network applet bytecode verification

Reproduced in: https: //www.cnblogs.com/binterminator/articles/1579028.html

Guess you like

Origin blog.csdn.net/weixin_30216687/article/details/94805622