Comparison between C ++ and Java 2

Source: Internet
Author: User
Tags java reference

Comparison between C ++ and Java 2

26. Java built-in multithreading support. You can inheritThreadClass to create a new thread (override the run () method ). Mutual exclusion occurs in useSynchronizedThe keyword is used as the object level of the type modifier. At any time, only one thread can access a specific objectSynchronizedMethod. In other words, whenSynchronizedFirst, the object will be "locked ".SynchronizedThe method also works, and "unlock" the object when exiting the method. No explicit locks; locks and locks are automatic. You still need to create your own "monitors" class to achieve more complex thread synchronization. The recursive synchronization method works normally. The time slice is not guaranteed between threads with the same priority.

27. Unlike C ++'s definition of using a control block, the access modifier (Public,Private, AndProtectedIs placed in the definition of each member in the class. No explicit access modifier. One element is "friendly" by default and can be accessed by other elements in the same package (they are equivalentYouyuan), But cannot be accessed by elements outside the package. Class, and each method in the class has an access qualifier to determine whether it is visible outside the file. SometimesPrivateKeywords are rarely used in Java, because "friendly" access permissions are more useful than removing access from other classes in the same package. (However, for multithreading,PrivateIs necessary .) JavaProtectedThe keyword indicates that "the successor and the class under the same package can be accessed ." In C ++ProtectedDifferent, C ++ stands for "only allow access by successors "(Private protectedIt is used to achieve the same effect, but the use of this keyword is canceled ).

28. Nested classes. In C ++, a nested class aims at name hiding and Code Organization (but the namespace of C ++ eliminates the need for name hiding ). The Java package mechanism provides effects similar to namespaces, so name hiding is not a problem for Java. The internal class of Java 1.1 looks like an embedded class. However, an internal class object is private and contains references to external class objects created by internal class objects. This means that internal class objects can access members of external class objects without restriction, as if those members directly belong to internal classes. This provides a more concise solution to the callback problem, and uses pointers in C ++ to solve the problem.

29. Because of the internal class described above, Java does not point to the member pointer.

30. There is no inline method. The Java compiler can decide to inline a method on its own, but you do not have much control over this. You can useFinalWe recommend that you inline a method with the keyword. However,InlineFunctions are only recommended for the C ++ compiler.

31. Java inheritance has the same effect as C ++, but the specific syntax is different. JavaExtendsKeywords to inherit from the base class, useSuperKeyword to call the method with the same name as the subclass in the base class (however, in JavaSuperKeywords only allow access to methods in the direct parent class, and can only be traced back to the upper level. In C ++, deeper basic class methods are allowed .) The constructor of the base class is also usedSuperKeyword call. As mentioned earlier, all classes are ultimately inherited fromObjectClass. Unlike C ++, Java does not explicitly construct the initialization list, but the Java compiler forces you to initialize the base class in the constructor method first, the compiler does not allow you to initialize the base class later. Java ensures the initialization of members by combining automatic initialization with non-initialized object reference exceptions.

public class Foo extends Bar {  public Foo(String msg) {    super(msg); // Calls base constructor    public baz(int i) { // Override      super.baz(i); // Calls base method    }  }}

32. Inheritance in Java does not change the protection level of the members in the base class. Different from C ++ in Java, you cannot specifyPublic,Private, OrProtectedInheritance. Similarly, the method to override the base class method cannot reduce the access permission of the base class method. For example, if the method in the base class isPublicIf you override this method, the access permission of the method you override must also bePublic(The compiler will check this ).

33. Java providesInterfaceKeyword to create a class similar to the abstract base class that only contains abstract methods and has no data members. This mechanism will only be designed as an interface andExtendsThe existing functions of keyword expansion are clearly divided. It is worth mentioning that,AbstractThe keyword will produce a similar effect, and the object of this class cannot be created. OneAbstractClasses can include Abstract METHODS (which are not required to be included), but can also contain implementations, which limits the single inheritance. The interface mechanism prevents virtual base classes like C ++.
UseImplementsKeyword to create instantiatedInterfaceVersion. Its Syntax looks similar to inheritance:

public interface Face {  public void smile();}public class Baz extends Bar implements Face {  public void smile() {    System.out.println("a warm smile.");  }}

34. None in JavaVirtualKeyword, because all non-static methods in Java use dynamic binding. Therefore, Java programmers do not need to decide whether to adopt dynamic binding. C ++ existsVirtualKeyword: this is because you can not use it for performance tuning to achieve slight performance improvement (or, in other words, "if you don't use it, you will be able to avoid it "), this usually causes confusion and accidents.FinalThe keyword provides some room for Performance Optimization-it allows the compiler to know that the modified method cannot be overwritten, so it may be statically bound (Inline, therefore, it is equivalent to a non-virtual method call of C ++ ). These optimizations depend on the compiler.

35. Java does not support multi-inheritance (MI), at least not in the same sense as C ++ (supported ). LikeProtected, MI seems quite good, but you know that you only need it when you face a design problem. Because Java uses a single inheritance, you will rarely encounter the need for MI.InterfaceKeywords are responsible for (allowing you to) combining (using) multiple interfaces.

36. The runtime type check function is very similar to that in C ++. To learn the referenceXYou can do this, for example:

X.getClass().getName();

You can perform a type-safe transformation as follows:

derived d = (derived)base;

It is the same as the forced type conversion in C. The compiler automatically calls the dynamic conversion mechanism without additional syntax. Although this does not benefit from the self-Interpretation of "new casts" in C ++, Java checks its usage and throws exceptions in a timely manner, and does not encounter conversion errors in C ++.

37. Java does not have destructor, so exception handling is different from that in C ++. You can addFinallyClause block to forcibly execute the necessary cleaning statement. All exception types in Java areThrowableClass subclass, which ensures that you have a common 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 exception  } finally {    mr.dispose(); // special cleanup  }}

38. Java exception specifications have great advantages over C ++. Unlike C ++, when a function is called at runtime, an exception is thrown when an error occurs, and the Java exception specification is verified and executed during compilation. In addition, the rewritten method must follow the exception specification: compared with the method to be rewritten in the base class, the rewritten method can throw an exception of the same type or its subtype as the method to be rewritten. This provides more robust exception handling code.

39. Java has method overloading, but there is no operator overloading.StringClass usage+And+ =AndStringThe expression uses automatic type conversion, but this is only a special built-in situation.

In 40. C ++ConstThe problem is naturally avoided in Java. You can only pass a reference to an object and will not automatically generate a local copy for you. You can callClone ()Generate a local copy of the parameter (althoughClone ()Poor mechanism design-see chapter 12th ).
The copy constructor is not automatically called in Java.
Create a compilation constant. You can do this:

static final int SIZE = 255;static final int BSIZE = 8 * 255;

41. For security issues, it is very important to compile a program and an applet. An important problem is that the applet won't let you write a disk, because it will allow a program to download from an unknown machine and dirty your disk. This situation changes somewhat with the application of Java 1.1 digital signature (digital signature) let you clearly know the special permissions that each program author has on your system (one of them may have corrupted your disk; you need to know which one and what happened .). Java 1.2 also promises more powerful support for applets.

42. Because Java is highly restrictive in some cases, you may be blocked from performing important tasks, such as directly accessing the hard disk. JavaNative methodTo solve this problem, you can use a local method to call programs written in another language (currently only C and C ++ are supported ). In this way, you can deal with platform-specific problems (in a relatively non-portable way, however, the Code is separate ). Applets cannot call local methods. Only applications can.

43. Java provides built-in support for annotation documents. Therefore, source code files can contain their own documents, which will be stripped by a program and reformatted as HTML. This is good news for document maintenance and use.

44. Java includes a standard library for solving specific tasks. C ++ relies on third-party non-standard libraries. These tasks include (or will soon include ):
-Network
-Database connection (through JDBC)
-Multithreading
-Distributed objects (through RMI and CORBA)
-Commerce
The practicality and standard nature of these libraries allow faster program development.

45. Java 1.1 includes the Java Beans standard, which can be used to create components in a visual programming environment. This promotes the development of visual components that can be used in all Developer development environments ). Because the visual components designed by Different developers are associated, this makes the components more selective and practical. In addition, the design of Java Beans is better understood by programmers. The component frameworks of specific developers often have steep learning curves.

46. If the access to the Java reference fails, an exception will be thrown. This will not occur before the reference is used. The Java specification only specifies that an exception must be thrown in some way. Many C ++ runtime systems can also throw exceptions for bad pointers.

47. In general, Java is more robust and relies on:
-Object Reference is initializedNull(A keyword)
-The reference will be checked and an exception will be thrown when it fails.
-All array accesses will be checked out of bounds.
-Automatic garbage collection mechanism to prevent memory leakage
-Simple and reliable Exception Handling
-Simple multi-threaded Language Support
-Network applets bytecode Verification

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.