04 – Classes

Classes in Java represent the way in which we organize our code. Each class should represent a logical or functional unit of code and a single program can consist of one or many classes. It’s important to code your classes as generically as possible so that they may be reused by other programs.

For the most part classes have a few simple rules to follow to be valid. Your class name should be the same as the name of the file that contains it. For example if you have a class name MyClass it should be in a file called MyClass.java. It is recommended that class names should be uppercase. The most basic Java class file looks like this:


// ExampleClass.java
public class ExampleClass {
}

As we mentioned before a class must have a main method with the exact signature above to be a program, but a program often consists of many classes put together, and only the main class needs to have the main method.

Classes often have another special method called the constructor. It is called whenever that class is instantiated, and all classes have them whether you’ve defined one or not (it’s inherited from the Object class, but you’ll learn more about that later). Because of this often a blank one is put into a class when it’s created specifically to avoid confusion.


// ExampleClass.java
public class ExampleClass {
  public ExampleClass() {
  }
}

You can see that the constructor looks similar to other methods, but it has no return type. Effectively it returns an instance of the class you are creating, so a return type would be inappropriate here. The constructor can take arguments, however, which could come in handy for setting initial conditions for a newly created object.