Kamis, 21 Juli 2011

Design aims

The differences between the C++ and Java programming languages can be traced to their heritage, as they have different design goals.
The different goals in the development of C++ and Java resulted in different principles and design trade-offs between the languages. The differences are as follows :

  • C++
  • Java
Compatible with C source code, except for a few corner cases. No backward compatibility with any previous language. The syntax is however strongly influenced by C/C++.
Write once compile anywhere (WOCA) Write once run anywhere / everywhere (WORA / WORE)
Allows procedural programming, object-oriented programming, and generic programming. Strongly encourages an object oriented programming paradigm.
Allows direct calls to native system libraries. Call through the Java Native Interface and recently Java Native Access
Exposes low-level system facilities. Runs in a protected virtual machine.
Only provides object types and type names. Is reflective, allowing metaprogramming and dynamic code generation at runtime.
Has multiple binary compatibility standards (commonly Microsoft and Itanium/GNU) Has a binary compatibility standard, allowing runtime check of correctness of libraries.
Optional automated bounds checking. (e.g. the at()vector and string containers) method in Normally performs bounds checking. HotSpot can remove bounds checking.
Supports native unsigned arithmetic. No native support for unsigned arithmetic.
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available as typedefs (uint8_t, ..., uintptr_t). Standardized limits and sizes of all primitive types on all platforms.
Pointers, References, and pass by value are supported Primitive and reference data types always passed by value.[1]
Explicit memory management, though third party frameworks exist to provide garbage collection. Supports destructors. Automatic garbage collection (can be triggered manually). Doesn't have the concept of Destructorfinalize() is not recommended. and usage of
Supports class, struct, and union and can allocate them on heap or stack Supports only class and allocates them on the heap. Java SE 6 optimizes with escape analysis to allocate some objects on the stack.
Allows explicitly overriding types. Rigid type safety except for widening conversions. Autoboxing/Unboxing added in Java 1.5.
The C++ Standard Library has a much more limited scope and functionality than the Java standard library but includes: Language support, Diagnostics, General Utilities, Strings, Locales, Containers, Algorithms, Iterators, Numerics, Input/Output and Standard C Library. The Boost library offers much more functionality including threads and network I/O. Users must choose from a plethora of (mostly mutually incompatible) third-party libraries for GUI and other functionality. The standard library has grown with each release. By version 1.6 the library included support for locales, logging, containers and iterators, algorithms, GUI programming (but not using the system GUI), graphics, multi-threading, networking, platform security, introspection, dynamic class loading, blocking and non-blocking I/O, and provided interfaces or support classes for XML, XSLT, MIDI, database connectivity, naming services (e.g. LDAP), cryptography, security services (e.g. Kerberos), print services, and web services. SWT offers an abstraction for platform specific GUIs.
Operator overloading for most operators The meaning of operators is generally immutable, however the + and += operators have been overloaded for Strings.
Full multiple inheritance, including virtual inheritance. Single inheritance only from classes, multiple from interfaces.
Compile time Templates Generics are used to achieve an analogous effect to C++ templates, however they do not translate from source code to byte code due to the use of Type Erasure by the compiler.
Function pointers, function objects, lambdas (in C++0x) and interfaces No function pointer mechanism. Instead idioms such as Interfaces, Adapters and Listeners are extensively used.
No standard inline documentation mechanism. 3rd party software (e.g. Doxygen) exists. Javadoc standard documentation
const keyword for defining immutable variables and member functions that do not change the object. final provides a limited version of const, equivalent to type* const pointers for objects and plain const of primitive types only. No constconst type* pointers. member functions, nor any equivalent to
Supports the goto statement. Supports labels with loops and statement blocks.
Source code can be written to be platform independent (can be compiled for Windows, BSD, Linux, Mac OS X, Solaris etc. without needing modification) and written to take advantage of platform specific features. Is typically compiled into native machine code. Is compiled into byte code for the JVM. Is dependent on the Java platform but the source code is typically written not to be dependent on operating system specific features.  

Syntax

  • Java syntax has a context-free grammar which can be parsed by a simple LALR parser. Parsing C++ is more complicated; for example, Foo<1>(3); is a sequence of comparisons if Foo is a variable, but it creates an object if Foo is the name of a class template.
  • C++ allows namespace level constants, variables, and functions. In Java, such entities must belong to some given type, and therefore must be defined inside a type definition - either a class, or an interface.
  • In C++, objects are values, while in Java they are not. C++ uses value semantics by default, while Java always uses references semantics. To have reference semantics in C++, both pointer or a reference can be used.
  • As a consequence, operator "." has a different meaning in each of these languages. In C++, it takes an object as the left operand and accesses a member of the object. In Java, it takes a reference to an object as the left operand and access a member of that object (the equivalent operator in C++ is "->", which takes a pointer as the left operand).
C++

class Foo {          // Declares class Foo
public:
    int x;           // Member variable
 
    Foo(): x(0) {}   //  Constructor for Foo, initializes x
 
    int bar(int i) { // Member function bar()
        return 3*i + x;
    }
};
Foo a; 
// declares a to be a Foo object value,
// initialized using the default constructor.
// Another constructor can be used as "Foo a(args);"
 
Foo b = a; 
// copies the contents of a to a new Foo object b;
// alternative syntax is "Foo b(a)"
 
a.x = 5; // modifies the object a
cout << b.x << endl; 
// outputs 0, because b is a 
// different object than a
 
Foo *c; 
// declares c to be a pointer to a 
// Foo object (initially
// undefined; could point anywhere)
 
c = new Foo; 
// binds c to reference a new Foo object
Foo *d = c; 
// binds d to reference the same object as c
c->x = 5; 
// modifies the object referenced by c
a.bar(5);  // invokes Foo::bar() for a
c->bar(5); // invokes Foo::bar() for *c
cout << d->x << endl; 
// outputs 5, because d references the
// same object as c
const Foo *a; // it is not possible to modify the object
              // pointed to by a through a
a = new Foo();
a->x = 5; 
// ILLEGAL
Foo *const b = new Foo(); 
// a declaration of a "const" pointer
b = new Foo(); 
//ILLEGAL, it is not allowed to re-bind it
b->x = 5; 
// LEGAL, the object can still be modified
 
 
Java  
 
class Foo {               // Defines class Foo
    public int x;         // Member variable, 
                          //initialized to 0 by default
 
    public Foo() {        // Constructor for Foo
    }
 
Foo a; 
// declares a to be a reference to a Foo object
a = new Foo(); 
// initializes using the default constructor
// Another constructor can be used as 
"Foo a = new Foo(args);"
    public int bar(int i) {// Member method bar()
        return 3*i + x;
    }
}
Foo b = a.clone(); 
// copies the values of all members
// of this instance if, and only if,
// Foo implements a public method called
// clone() which returns a new copy of the object
a.x = 5; // modifies the object a
System.out.println(b.x); 
// outputs 0, because b points to a
// different object than a
Foo c; 
// declares c to be a reference to a Foo 
// object (initially null if c is a class member; 
// it is necessary to initialize c before use
// if it is a local variable)
c = new Foo(); 
// binds c to reference a new Foo object
Foo d = c; 
// binds d to reference the same object as c
c.x = 5; 
// modifies the object referenced by c
a.bar(5); // invokes Foo.bar() for a
c.bar(5); // invokes Foo.bar() for c
System.out.println(d.x); 
// outputs 5, because 
// d references
// the same object as c
final Foo a; // it is possible to modify the object
a = new Foo(); // Only in constructor
a.x = 5; 
// LEGAL, the object can still be modified
final Foo b = new Foo(); 
// a declaration of a "final" reference
b = new Foo(); 
// ILLEGAL, it is not allowed to re-bind it
b.x = 5; 
// LEGAL, the object can still be modified
 

1 komentar: