MC logo
C++ v. Java Classes I
[^] CSc 220 Home
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Plain Structs] [Point With Struct] [C++ Point Class] [Linked List (Structs)] [Linked List (Classes)] [C++ v. Java Classes I] [Prime Generator Algorithm] [Fast Primes Generator]
Here are some differences between C++ and Java classes. (We'll have more when we get to inheritance.)
  1. You must put a semicolon after C++ class definitions, but not after Java classes.
  2. 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.
  3. 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.
  4. 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:
    1. 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++.)
    2. Assignment of object variables in C++ copies the object. For C++ objects, x = y; is closer to x = y.clone(); in Java.
    3. Likewise, Java arrays are always arrays of references. In C++, they are arrays of the objects themselves.
  5. Java and C++ both use a dot (.) to select a field in an object.
  6. Java also uses the dot to select a field in a class, while C++ uses the :: operator. (C++ also uses :: with namspaces.)
  7. 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).
  8. C++ has destructors. Java does not, though there is a way to provide cleanup by overriding a method of Object.
  9. The constant method declaration is not available in Java.