Compare C + + and Java

Source: Internet
Author: User
Tags abstract define arithmetic final garbage collection thread thread class throwable

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

However, there are still some notable differences between C + + and Java. It can be said that these differences represent a great improvement in technology. Once we figure out these differences, we'll understand why Java is a good programming language. This appendix will guide you through some of the key features used to differentiate between Java and C + +.
(1) The biggest hurdle is speed: The interpreted Java is about 20 times times slower than the C execution speed. Nothing can prevent the Java language from compiling. When writing this book, some quasi real-time compilers have just appeared, which can significantly speed up. Of course, we have every reason to think that there will be pure intrinsic compilers for more popular platforms, but without those compilers, there must be some problems that Java cannot solve due to speed constraints.
(2) Like C + +, Java also provides two types of annotations.
(3) Everything must be placed in a class. No global functions or global data exist. If you want to get the functionality equivalent to a global function, consider placing the static method and the static data in a class. Note that there is no such thing as structure, enumeration, or union, and that all is only "class"!
(4) All methods are defined in the body of the class. So in the eyes of C + +, it seems that all functions are embedded, but the truth is not how (the embedded problem is described later).
(5) In Java, class definitions take almost the same form as C + +. But no sign ends the semicolon. There is not class Foo in this form, only the class definition.

Class Atype ()
void Amethod () {/* method principal */}
}

(6) There is no scope scope operator "::" in Java. Java uses dots to do everything, but you don't have to think about it, because you can only define elements in one class. Even those method definitions must be within a class, so there is no need to specify scope for scopes. One of the differences we notice is a call to the static method: Using Classname.methodname (). In addition, the name of the package (package) is established with the dot number, and can use the Import keyword to achieve C + + "#include" part of the function. For example, the following statement:
Import java.awt.*;
(#include并不直接映射成import, but with a similar feeling when used. )
(7) similar to C + +, Java contains a series of "Master Types" (primitive type) for more efficient access. In Java, these types include boolean,char,byte,short,int,long,float and double. The size of all primary types is intrinsic and independent of the specific machine (considering the problem of porting). This will certainly have a certain impact on performance, depending on the different machines. Checking and asking for types is becoming more demanding in Java. For example:
A conditional expression can only be a Boolean (Boolean) type, and an integer cannot be used.
You must use the result of an expression like x+y; you can't just use "x+y" to implement "side effects."
(8) the char (character) type uses the internationally available 16-bit Unicode character set, so it can automatically express most of the country's characters.
(9) statically referenced strings are automatically converted to string objects. and C and C + +, there is no independent static character array string to use.
Java added three right shift operator ">>>" with a function similar to the "logical" right shift operator, which inserts a value of 0 at the end. ">>" Inserts a sign bit (or "arithmetic" shift) at the same time as the shift.
(11) Although superficially similar, Java arrays use a rather different structure than C + + and have unique behavior. There is a read-only length member, through which you know how large the array is. And once the array bounds are exceeded, the runtime check automatically discards an exception. All arrays are created in the memory heap, and we can assign one array to the other (simply copy the array handle). An array identifier is a first-level object, and all of its methods usually apply to all other objects.
(12) For all objects that are not of the main type, they can only be created with the new command. Unlike C + +, Java has no corresponding command to create objects that are not of the main type on the stack. All primary types can only be created on the stack without using the new command. All major classes have their own "wrapper" classes, so you can create equivalent, memory-heap based objects with new (an exception to the main type array: They can be assigned as C + + by initializing the collection, or using new).
No advance declaration is required in Java. If you want to use a class or method before you define it, just use it directly--the compiler will ensure that the appropriate definition is used. So unlike in C + +, we don't run into any issues involving early references.
Java does not have a preprocessing machine. To use a class in another library, simply use the Import command and specify the library name. There is no macro similar to preprocessor.
Java uses a package instead of a namespace. Since everything is placed in a class, and because of a mechanism called "encapsulation" that can perform a namespace-like decomposition of the class name, the naming problem is no longer in our consideration. The packet also collects the components of the library under a single library name. We simply import a package and the rest of the work is done automatically by the compiler.
(16) An object handle defined as a class member is automatically initialized to null. Initialization of basic class data members is reliably guaranteed in Java. If you do not explicitly initialize them, they will get a default value (0 or equivalent). They can be explicitly initialized (explicitly initialized): they are either defined within the class or defined in the builder. The syntax is easier to understand than C + + syntax and is fixed for both static and non-static members. We don't have to define the way that static members are stored externally, which is different from C + +.
(17) In Java, there are no pointers like C and C + +. When you create an object with new, you get a reference (which this book always refers to as "handle"). For example:
string s = new String ("Howdy");
However, C + + references must be initialized at the time of creation and cannot be redefined to a different location. However, Java references are not necessarily limited to where they were created. They can be defined according to circumstances, which eliminates part of the need for pointers. Another reason for the large number of pointers in C and C + + is to be able to point to any one memory location (which in turn makes them unsafe and why Java does not provide this support). Pointers are often viewed as an effective means of moving around in an array of basic variables. Java allows us to achieve the same goal in a more secure form. The ultimate way to solve the pointer problem is the "intrinsic approach" (discussed in Appendix A). When you pass a pointer to a method, it usually does not cause much of a problem because there are no global functions at this time, only classes. And we can pass a reference to the object. The Java language begins by claiming that it "doesn't use pointers at all!" "But as many programmers are questioning how to work without pointers?" It was later declared that "the use of restricted pointers". You can decide for yourself whether it is "true" is a pointer. However, no pointer "arithmetic" exists in any case.
Java provides a "builder" (constructor) similar to C + +. If you do not define one yourself, you will get a default builder. If you define a Non-default builder, you will not automatically define the default builder for us. This is the same as C + +. Note The builder is not replicated because all the arguments are passed by reference.
There is no "destructor" in Java. There is no "scope" problem with the variable. The "presence time" of an object is determined by the time of the object's existence, not by the garbage collector. There is a finalize () method that is a member of each class, and is somewhat similar to the "destruction" of C + +. However, Finalize () is called by the garbage collector and is responsible only for releasing "resources" (such as open files, sockets, ports, URLs, and so on). To do something in a particular place, you must create a special method and call it, and you cannot rely on finalize (). On the other hand, all objects in C + + (or "should") will be corrupted, but not all objects in Java will be collected as "garbage". Because Java does not support the concept of a break, you must carefully create a purge method when necessary. And for the underlying classes within the class and the member objects, you need to explicitly call all the cleanup methods.
Java has the method "overload" mechanism, which works almost exactly the same as the overload of C + + functions.
Java does not support default arguments.
There is no goto in Java. The unconditional jump mechanism it takes is "break tag" or "Continue standard", which is used to jump out of the current multiple nested loops.
Java employs a hierarchical hierarchy of single radicals, so all objects are uniformly inherited from the root class object. In C + +, we can start a new inheritance tree anywhere, so we end up seeing "a forest" that contains a lot of trees. In Java, we have only one hierarchical structure in any case. Although this appears to be a limitation, it is often possible to gain greater power because we know that each object must have at least one object interface. C + + currently appears to be the only OO language that does not have a single root structure enforced.
Java does not have templates or other forms of parameterized types. It provides a series of collections: Vector (vector), stack (stack), and Hashtable (hash table), which holds the object reference. With these sets, our set of requirements can be met. These collections are not, however, designed for quick calls like the real phenomenon C + + Standard Template Library (STL). The new collection in Java 1.2 appears more complete, but still does not have the efficient use of authentic templates.
(25) "garbage collection" means that there will be much less memory vulnerabilities in Java, but it is not entirely impossible (the garbage collector cannot keep track of it if you call an intrinsic method for allocating storage space). However, memory vulnerabilities and resource vulnerabilities are caused by poorly written finalize () or by releasing a resource at the end of an allocated block (the "wreck" is particularly handy at this point). Garbage collector is a great progress on the basis of C + +, which makes many programming problems disappear from the invisible. But it is not appropriate for a handful of garbage collectors to have problems with the force. But the many advantages of the garbage collector make this shortcoming seem insignificant.
The support for multithreading is built in Java. With a special thread class, we can create a new thread by inheriting (the run () method is discarded). If the synchronized (sync) keyword is used as a type limiter for a method, the mutual exclusion occurs at the object level. At any given time, only one thread can use the synchronized method of an object. On the other hand, when a synchronized method enters, it first "locks" the object, preventing any other synchronized method from using that object. The object is "unlocked" only if you exit this method. Between threads, we are still responsible for implementing more complex synchronization mechanisms by creating our own "monitor" classes. The recursive synchronized method can function normally. If the priority level of the thread is the same, the "fragmentation" of time is not guaranteed.
(27) Instead of controlling the declaration code block like C + +, we place the Access qualifier (public,private and protected) into the definition of each class member. If you do not specify an "explicit" qualifier, the default is "friendly" (friendly). This means that other elements in the same package can also access it (equivalent to being a "friends" of C + +-friends), but not accessible by any element outside the package. Class--and every method within a class--has an access qualifier that determines whether it can be "visible" outside the file. Private keywords are often rarely used in Java, because "friendly" access is often more useful than accessing other classes in the same package. However, in a multi-threaded environment, the proper use of private is very important. The Java protected keyword means "accessible by inheritors and accessed by other elements in the package." Note that Java does not have elements equivalent to the protected keyword of C + +, which means "access only by Inheritors" (previously available as "private protected", but the combination of this pair of keywords has been canceled).
(28) Nested classes. In C + +, nesting a class helps to hide names and facilitates the organization of the Code (but the C + + namespace makes it redundant to hide names). Java's "encapsulation" or "package" concepts are equivalent to the C + + namespace, so it is no longer a problem. Java 1.1 introduces the concept of "inner class", which keeps a handle to the outer class in secret-needed when creating an internal class object. This means that the inner class object may be able to access members of the external class object without any conditions-as if those members were directly subordinate to the inner class object. This provides a better solution for the callback problem--c++ is resolved with a pointer to a member.
(29) There is no pointer to a member in Java because of the internal class described above.
There is no "embed" (inline) method in Java. The Java compiler may decide to embed a method on its own, but we have no more control over it. In Java, you can use the final keyword for a method to "suggest" an embedding operation. However, embedding functions is also a recommendation for C + + compilers.
Inheritance in Java has the same effect as C + +, but uses different syntax. Java uses the Extends keyword flag to inherit from a base class and, using the Super keyword, indicates the method to be invoked in the underlying class, which has the same name as the method we are currently in (however, the Super keyword in Java only allows us to access the method of the parent class- That is, the hierarchical structure of the previous level). By setting the scope of the underlying class in C + +, we can access the methods that lie deeper in the hierarchy. The base class Builder can also be invoked with the Super keyword. As noted earlier, all classes will eventually be automatically inherited from object. Unlike C + +, there is no explicit builder initialization list. But the compiler forces us to initialize all of the underlying classes at the beginning of the builder body, and does not allow us to do this in the latter part of the body. By combining automatic initialization and exceptions from uninitialized object handles, the initialization of members can be effectively guaranteed.


public class Foo extends Bar {
  public foo (String msg) {
    super (MSG);//Calls BAS E constructor
 }
  public baz (int i) {//Override
    Super.baz (i);//Calls Base M Ethod
 }
}


Inheritance in Java does not change the level of protection for the underlying class members. We cannot specify public,private or protected inheritance in Java, which is the same as C + +. In addition, priority methods in derived classes do not reduce access to the underlying class methods. For example, suppose a member is public in the underlying class, and we replace it with another method, the method used for the substitution must also belong to public (the compiler will automatically check).
Java provides a interface keyword that is the equivalent of creating an abstract base class. The abstract method is populated with no data members. As a result, there is a significant difference between what is designed to be just one interface and the extension of the existing functionality based on the extends keyword. It is not worth using the abstract keyword to produce a similar effect because we cannot create an object that belongs to that class. An abstract (abstract) class can contain abstractions (although it does not require anything in it), but it can also contain code for concrete implementations. Therefore, it is limited to a single inheritance. This scheme avoids the need for some mechanisms like the C + + virtual base class by using it in conjunction with the interface.
To create a interface (interface) version that can perform an "example" (that is, to create an instance), you need to use the Implements keyword. Its syntax is similar to the inherited syntax, as follows:
Public interface Face {
public void smile ();
}
public class Baz extends Bar implements face {
public void Smile () {
System.out.println ("A Warm Smile");
}
}


There is no virtual keyword in Java because all non-static methods are sure to use dynamic binding. In Java, programmers do not have to decide for themselves whether to use dynamic binding. C + + uses virtual, because we can adjust the performance of the time, by omitting it, so as to achieve a small amount of elevation of execution efficiency (or in other words: "If not, there is no need for it to pay the price"). Virtual often creates some degree of confusion and results in unpleasant consequences. The final keyword provides some scope for performance tuning-it indicates to the compiler that this method cannot be superseded, so its scope may be statically constrained (and become embedded), so the equivalent of C + + non-virtual invocation is used. These optimizations are done by the compiler.
Java does not provide multiple inheritance mechanisms (MI), at least not as C + + does. Like protected, MI is a good idea on the surface, but only when you really face a particular design problem do you know that you need it. Because Java uses a "single root" hierarchy, MI is needed only on a rare occasion. The interface keyword will help us automate the merging of multiple interfaces.
(36) The type identification function of the runtime is very similar to C + +. For example, to get information about handle x, you can use the following code:
X.getclass (). GetName ();
For a "type-safe" tightening styling, you can use:
Derived d = (derived) base;
This is the same with the old style C styling. The compiler automatically invokes the dynamic modeling mechanism and does not require additional syntax. Although it does not have the advantage of easy positioning styling like C + + 's "new Casts", Java examines usage and discards those "exceptions", so it does not allow bad styling as C + + does.
Java takes a different exception control mechanism because the builder is no longer present at this time. You can add a finally clause to enforce specific statements to perform the necessary cleanup work. All the exceptions in Java are inherited from the underlying class throwable, so we can ensure that we get a generic interface.
public void F (OBJ b) throws IOException {
MyResource Mr = B.createresource ();
try {
Mr. Useresource ();
catch (MyException e) {
Handle my exception
catch (Throwable e) {
Handle all other exceptions
finally {
Mr.dispose (); Special cleanup
}
}


Java's exception specification is much better than C + +. After discarding an error exception, the Java exception specification is checked and executed during compilation, instead of calling a function during runtime, as in C + +. In addition, the substituted method must follow the exception specification of the underlying class version of the method: they can discard the specified exception or other exceptions derived from those exceptions. In this way, we end up with a more "robust" exception control code.
Java has the ability to overload a method, but does not allow operator overloading. The string class cannot concatenate different strings with the + + + + operator, and string expressions use automatic type conversions, but that is a special kind of built-in condition.
(40) through the prior agreement, C + + frequently appear in the const problem in Java has been controlled. We can only pass a handle to the object, and the local copy will never be generated automatically for us. If you want to use a technique like C + + by value, call Clone () and generate a local copy of the argument (although the design of the Clone () is still rough-see chapter 12th). There is no replica builder that is automatically invoked at all. To create a constant value for a compilation period, you can encode as follows:
static final int SIZE = 255
static final int bsize = 8 * SIZE
(41) Due to security reasons, there are significant differences between the programming of "application" and the programming of "program piece". One of the most obvious problems is that the patch does not allow us to write on the disk, because doing so would cause unknown programs to be downloaded from the remote site that might be fiddling with our disks. This has changed with Java 1.1 's reference to digital signature technology. Depending on the digital signature, we know exactly how all the authors of a piece of the program are, and verify that they are authorized. Java 1.2 will further enhance the ability of the program tablet.
(42) Because Java may appear to be too restrictive on some occasions, it is sometimes reluctant to perform important tasks such as direct access to hardware. The Java solution to this problem is the "intrinsic approach", which allows us to invoke functions written in other languages (currently only supports C and C + +). In this way, we are sure to be able to solve platform-related problems (in a form that is not portable, but that code will then be isolated). A slice cannot invoke an intrinsic method, only an application can.
Java provides built-in support for annotation documents, so source files can also contain their own documents. Through a separate program, these document information can be extracted and reformatted into HTML. This is undoubtedly a great progress in document management and application.
Java contains a number of standard libraries for accomplishing specific tasks. C + + relies on a few non-standard libraries provided by other vendors. These tasks include (or will soon be included):
Web-connected
Database connection (via JDBC)
Multithreaded
Distributed objects (via RMI and CORBA)
Compression
Trade
Because these libraries are easy to use and very standard, they can greatly speed up the development of applications.
Java 1.1 contains the Java Beans Standard, which creates components that can be used in a visual programming environment. By complying with the same standards, visual components can be used in all vendors ' development environments. Because we do not rely on a vendor's solution for visual component design, there is a greater choice of components and improved component performance. In addition, the Java beans is designed to be simple and easy for programmers to understand, while specialized component frameworks developed by different vendors require more in-depth learning.
(46) If access to the Java handle fails, an exception is discarded. This discard test does not have to happen just before a handle is used. According to Java design specifications, only that the exception must be discarded in some way. Many C + + Run-time systems can also discard exceptions caused by pointer errors.
Java is usually more robust, by doing the following:
Object handle initialized to null (one keyword)
Handle is sure to be checked and thrown out when an error occurs
All array accesses are checked to detect boundary violations in a timely manner
Automatic garbage collection to prevent memory leaks
A clear and "fool-type" anomaly control mechanism
Provides simple language support for multithreading
BYTE-code checksum for network patches

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.