C++ v. Java Classes I
Here are some differences between C++ and Java classes. (We'll have more
when we get to inheritance.)
- You must put a semicolon after C++ class definitions, but not after
- C++ has no requirements relating file names and class names. You can
put your C++ class anywhere that makes it visible to the code which uses it.
- In C++, the public, private and protected keywords
are used with a colon and apply to all declarations in the class until
changed. In Java, each member needs to be declared separately.
- In Java, a variable declared of class type T
contains a Java reference to an object of type T.
In C++, a variable declared of class type T
actually contains the object, not a reference.
(In Java, no type of variable can actually contain an object.
References are always used.) Some consequences:
- Java objects must always be created with new.
C++ objects need not be. (This is similar to the situation with arrays,
though they are not considered objects in C++.)
- Assignment of object variables in C++ copies the object. For C++
objects, x = y; is closer to x = y.clone(); in Java.
- Likewise, Java arrays are always arrays of references. In C++, they
are arrays of the objects themselves.
- Java and C++ both use a dot (.) to select a field in an object.
- Java also uses the dot to select a field in a class, while
C++ uses the :: operator. (C++ also uses :: with namspaces.)
- C++ uses the operator -> instead of the dot when starting
from a pointer to an object instead of from an object itself. Depending on
how you look at it, this situation
either just doesn't occur in Java (since it hasn't pointers), or Java uses
the dot here (since a Java object
reference is more like a C++ pointer to an object
than it is like a C++ object variable).
- C++ has destructors. Java does not, though there is a way to provide
cleanup by overriding a method of Object.
- The constant method declaration is not available in Java.