Comparison of Java and C++: Difference between revisions

Content deleted Content added
m Syntax: change width
Syntax: merge tables
Line 112:
|-
| <syntaxhighlight lang="cpp">
class Foo { // Declares class Foo
int x = 0; // Private Member variable. It will
// be initialized to 0, if the
// constructor would not set it.
// (from C++11)
public:
Foo(): x{0} // Constructor for Foo; initializes
{} // x to 0. If the initializer were
// omitted, the variable would
// be initialized to the value that
// has been given at declaration of x.
 
int bar(int i) { // Member function bar()
return 3 * i + x;
}
};</syntaxhighlight>
| <syntaxhighlight lang="java">
class Foo { // Defines class Foo
private int x; // Member variable, normally declared
// as private to enforce encapsulation
// initialized to 0 by default
 
public Foo() { // Constructor for Foo
} // no-arg constructor supplied by default
 
public int bar(int i) { // Member method bar()
Line 245:
// outputs 5, because d references the
// same object as c</syntaxhighlight>
|}
* In C++, it is possible to declare a pointer or reference to a [[const]] object in order to prevent client code from modifying it. Functions and methods can also guarantee that they will not modify the object pointed to by a pointer by using the "const" keyword. This enforces [[const-correctness]].
* In Java, the <code>final</code> keyword is similar to the <code>const</code> keyword in C++, but its usage is more limited.{{sfn|Goetz|Peierls|Bloch|Bowbeer|2006|loc=§3.4.1 Final fields|p=48}} For the most part, const-correctness must rely on the semantics of the class' interface, i.e., it is not strongly enforced, except for public data members that are labeled <code>final</code>.
 
{| class="wikitable"
! style="width:600px;"| C++
! style="width:600px;"| Java
|-
*| In C++, itIt is possible to declare a pointer or reference to a [[const]] object in order to prevent client code from modifying it. Functions and methods can also guarantee that they will not modify the object pointed to by a pointer by using the "const" keyword. This enforces [[const-correctness]].
| <syntaxhighlight lang="cpp">
const Foo* a; // it is not possible to modify the object
// pointed to by a through a
</syntaxhighlight>
 
|<syntaxhighlight lang="java">
*| In Java, theThe <code>final</code> keyword is similar to the <code>const</code> keyword in C++, but its usage is more limited.{{sfn|Goetz|Peierls|Bloch|Bowbeer|2006|loc=§3.4.1 Final fields|p=48}} For the most part, const-correctness must rely on the semantics of the class' interface, i.e., it is not strongly enforced, except for public data members that are labeled <code>final</code>.
|<syntaxhighlight lang="java">
final Foo a; // a declaration of a "final" reference:
// it is possible to modify the object,