User Tools

Site Tools


This is an old revision of the document!

Java Quick Reference

This page holds notes that I've made whilst brushing up on my Java. It may be useful to anybody else who's coming from a C++ background, but it's unlikely to be of interest to anybody who's already familiar with Java basics, or whose learning it as a first language.

Classes and Scopes

In Java everything is defined within a class - functions cannot exist without being wrapped in some sort of class definition.

Definitions default to package-private, which is to say they're globally available to any classes and methods in the same package, but not outside it. This scope can be modified by standard C++ keywords:

public Globally available.
protected Available to subclasses.
private Hidden from subclasses, available to inner classes (see Nested Classes).

Nested Classes

Nesting of class definitions has similar effects to friend declarations in C++, where nested classes that are created within an instance of the outer class have an implicit reference to that instance and can access even private members of that instance. In Java this is known as an inner class.

This applies unless the nested class is declared static, in which case it can only access static members of the outer class (this isn't known as an “inner class”, only non-static nested classes are inner classses).

Special cases of inner classes are local classes, where the class is declared within a method definition, and anonymous classes which allow an anonymous subclass to be created.

The code block below illustrates inner, local and anonymous classes:

class Outer
    private int counter;
    class InnerClass
        public void innerMethod()
            counter += 10;
    public void method()
        class LocalClass
            public void localMethod()
                counter *= 2;
        InnerClass innerInstance = new InnerClass();
        // This will add 10 to counter.
        LocalClass localInstance = new LocalClass();
        // This will then double counter.
        // Create anonymous class which inherits from LocalClass
        // and overrides localMethod().
        LocalClass anonymousInstance = new LocalClass() {
            public void localMethod()
                counter *= 3;
        // This will then triple counter.



quickref/java.1366027067.txt.gz · Last modified: 2013/04/15 11:57 by andy