Classes in Java

Here is most of what you need to know about Java classes in twenty bullet points.

The Details

  1. Java programs are made up (entirely) of classes grouped into packages.
  2. An object is an instance of a class.
        public class Circle { ... }
        Circle c1 = new Circle(...);
        Circle c2 = new Circle(...);
  3. A class can extend another class (called its superclass) and can also implement zero or more interfaces.
        class Shape { ... }
        class Circle extends Shape { ... }
        interface Drawable { ... }
        interface Saveable { ... }
        class SuperDuperCircle extends Circle implements Drawable, Saveable { ... }
  4. A class has members. Members can be fields, methods, or constructors. A class can also be defined inside another class, in which case it is called an inner class. Classes can also contain instance initializers and static initializers.
        class Shape {
            private Color color;                      // field
            public Shape(Color c) {color = c;}        // constructor
            static { System.out.println("Shapes!"); } // static initializer
            { System.out.println("Made a shape"); }   // instance initializer
            public Color getColor() {return color;}   // method
  5. Fields can be instance variables or class variables.
        class C {
            int x;              // instance field
            static int y;       // class field (shared among all instances)
        C a = new C();
        C b = new C();
        a.x = 1;
        b.x = 2;
        a.y = 3;
        b.y = 4;
        // Now a.x == 1, b.x == 2, a.y == 4, b.y == 4, C.y == 4
  6. Methods can be instance methods or class methods (the term "function" is not used in Java).
  7. Constructors are NOT methods.
  8. In the declaration of a class or member the entity can be marked with zero or more modifiers. (But private, protected and public are supposed to be mutually exclusive.)

    Class Modifiers
    no modifieraccessible only within its own package
    publicaccessible wherever its package is
    abstractcannot be instantiated (may have abstract methods)
    finalcannot be extended (subclassed)
    staticmakes an inner-declared class really a top-level one
    Member Modifiers
    privateaccessible only within its class
    no modifieraccessible only within its package
    protectedaccessible only within its package and to its subclasses
    publicaccessible wherever its class is
    Field Modifiers
    finalvalue may not be changed, once assigned
    staticonly one instance of the field shared by all objects of the class
    transientfield is not serialized
    volatilevalue may change asynchronously compiler must avoid certain optimizations
    Method Modifiers
    finalmay not be overridden
    staticmethod does not apply to a particular instance
    abstracthas no body; subclasses will implement
    synchronizedrequires locking the object before execution
    nativeimplementation is not written in Java, but rather in some platform dependent way
  9. An abstract class can not have any instances, so you have to subclass it to make it useful. A final class cannot be subclassed.
  10. There are five kinds of classes: package-level, nested top-level, member, local or anonymous.
     * A throw-away class that illustrates the five kinds of Java classes.
     * 'A' is a package-level class, 'B' is a nested top-level class,
     * 'C' is a local class, 'D' is a local class, and there is an
     * anonymous class that is a subclass of Thread.
    class A {
        int x;
        static class B {
            int x;
        class C {
            int x;
            int sum() {return x + A.this.x;}
        void f() {
            class D {
               int x;
            D d = new D();
            Thread e = new Thread() {
                public void run() {
                    System.out.print("Hello from " + getName());
     * Application that shows off how one would use the demo class above.
    public class ClassExample {
        public static void main(String[] args) {
            A a = new A();
            a.x = 1;
            A.B b = new A.B();
            b.x = 2;
            A.C c = C();
            c.x = 3;
  11. There is a cosmic base class called Object (defined in the package java.lang). Every class (except Object) is a direct or indirect subclass of Object.
  12. There is also a class called Class. Every class is an object of the class Class. You can get the class of an object x with x.getClass(). If c is the name of a class (or a primitive type) you can write c.class.
  13. You can override Object.finalize() for cleaning up resources, BUT DON'T!!!!!! (Bloch, p. 20)
  14. Every object in Java has a monitor which can be locked and unlocked by entering and leaving, respectively, a synchronized statement. In addition, condition synchronization comes for free since wait() and notify() are methods of the class Object.
  15. Making a class immutable takes a little bit of effort. Follow these four rules:
    • Provide absolutely NO mutators.
    • Ensure no methods can ever be overridden: either make the class final, make every method final, or hide the constructors and expose only static factory methods.
    • Make all fields private and final.
    • Watch out for mutable components! If you have a field of a mutable class make a defensive copy in constructors, accessors and readObject.
  16. Classes can be parameterized with types
    class Greeter<V> {
        private V target;
    class Pair<T1, T2> {
        private T1 first;
        private T2 second;
  17. Parameterized types are instantiated in several ways:
        Greeter<Integer> r1 = new Greeter<Integer>();
        Greeter<?> r2 = new Greeter<String>();
        Greeter<? extends JComponent> r3 = new Greeter<JCheckBox>();
        Greeter<? super Graphics2D> r4 = new Greeter<Graphics>();
  18. Methods can be parameterized, too.
    public class CollectionUtil {
        public static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
            for (T o : a) {
  19. For more on parameterized types see the short section on generics in the Java Tutorial, or the long section on generics in the Java Tutorial.
  20. To write non-trivial Java applications, you need to understand a little bit about classloaders and classpaths.

A Puzzler

Try to figure out what this program does, without running it. After you think you have your answer, run it to see if you are right.
public class T {
    private final String name;

    private void printName() {

    public T(String name) { = name;

    public static void main(String[] args) {
        new T("main").doIt();

    private void doIt() {
        new T("doIt") {
            void method() {