Classes

A Java class is very similar to a C++ class. There are minor syntax differences, covered elsewhere. There are also a small number of conceptual differences.

The major difference is that a Java class is entirely defined within a single .java file, there is no concept of a definition (header file) and an implementation (C++ file). That is covered in a separate topic.

Class source files

Each Java class must be stored in its own separate file, you are not allowed to place more than one class in the same file. The file must have the same name. Eg the Java class MyClass must be stored in the file MyClass.java.

Many C++ programmers follow similar rules, but it is not enforced by the compiler. There is always a temptation to include several related classes in the same file, especially if they are small. In Java, the compiler will give an error if a class is declared in a file with a different name.

Since a Java class is defined and implemented in the same file, it is not possible to split the implementation across multiple files. With C++, the class must be fully defined in a single header file, but it is possible to spread the implementation across multiple C++ files.

Compiled classes

The Java compiler creates a .class file for each class, with the same name as the original .java file (eg MyClass.java compiles to MyClass.class). The .class files contain Java byte code for the compiled Java class.

Unlike C++, classes are never statically linked to form libraries. Every class is dynamically loaded individually.

Summary

Key differences between C++ and Java:

  • Java doesn't separate the class definition from the implementation.
  • Java enforces one class per file, with consistent file naming.
  • Classes are dynamically loaded, individually.