Skip to content

Classes and Files

Estimated time to read: 2 minutes

Overview

  • In general, each Java class is stored in its own file.
  • The source file format is classname.java.
  • Note that the filename is case sensitive and should follow the same naming scheme of the class that it contains.
  • Compiled source files will have the same name as the .java file it was compiled from, but, with an extension of .class

Declaring a class

When you declare a class, there are various things that must be present or that can be stated about the class.


  • Public - The class will be visible throughout the runtime environment
  • Protected - The class will not be visible throughout the runtime environment

  • Abstract - Abstract classes can not be instantiated

  • Final - Rarely done. A class that you can not create a subclass of.

  • Extends - This is inheritance from another class. You can not inherit directly from more than one base class.
  • Fun fact! Every class in Java extends java.lang.object. If you don't extend a class, Java will automatically assume that it extends java.lang.object for you.

  • Implements - Syntactically, this is where interfaces are specified. Multiple can be defined through the use of a comma separated list.

  • Class body - The body of the class goes between the parenthesis

Example

<public> <abstract> <final> class className
     <extends superclassName>
     <implements interfaceName>
     {
       // class body
     }

The angle brackets indicate optional components. Most classes will be created as public.

A simple class

Below is the outline of a Car class with no attributes of methods.

This class definition would be defined in a file named Car.java

public class Car {

}

Putting Classes in a Package

  • Classes should always be placed in a package.
  • This is not mandatory, but is highly encouraged.
  • Packages allow you to organise the classes that make up an application.

The first line of the .java file should be the package declaration.

The example below has the class named Car placed into a package named io.entityfour:

package io.entityfour;

public class Car {

}