Java: Classes/Objects

Simple class

package myPackage;

public class Hello {
	public static void main(String[] args) {
		Hello newHelloObj = new Hello("Hello World!");  // instantiated object
		newHelloObj.printOut();                         // calls print method
	}

	private String instanceValue;                           // Object memory

	public Hello(String constructorParm){                   // Object Constructor
		this.instanceValue = new String(constructorParm);
	}

	private void printOut(){                                // Object Method
		System.out.println(instanceValue);
	}
}

A single file can have many classes, only one can be public.

Identifiers (class names, variables names etc)

  • can include letter, $ or underscore
  • numbers acceptable but not at start
  • not a Java keyword
  • normally camelCase
  • “static final” & enum values: SNAKE_CASE

Access modifiers

publicGlobally visible
protectedVisible in current package & in sub-classes
(none specified / default)AKA “package-private”. Visible in current package only
privateNot visible outside current class

Additional Specifiers

staticClass-level only, not present on each instance/object
abstractNot yet implemented, must be implemented by subclass
finalCannot be overridden
synchronisedOnly one thread can call at a time, will complete execution before release
nativeUsed for interacting with native (e.g. C/C++) libraries
strictfpStrict floating point arithmetic

Initialisation

Class Initialisation

  1. if superclass is defined – initialise parent class first
  2. initialise static variables in order declared
  3. call static “initialiser” if present

Object / Instance Initialisation

  1. if superclass is defined – initialise parent object first
  2. initialise instance variables in order declared
  3. call instance initialiser if present
  4. call constructor (including superclass constructors referenced with this() )

Constructors

  • First line must be overloaded constructor this(…) or parent constructor super(…)
  • → no-arg super constructor will be inserted by default (if no this() or super())
  • → if no-arg super() not present then (A) an explicit constructor is required and (B) it must start with this(…) or super(…)
  • → calling this(…) or super(…) after first line is not permitted
  • if only private constructors are defined, the class cannot be inherited
  • “final” instance variables must be initialised by the end of the constructor

Inheritance

Overloading vs Overriding

  • overloading: in same class, same method name, different parameters
  • overriding: in child class, same method name & parameters, different logic

Variables

Variables are not overridden. They are “hidden”. In general it is best not to create variables of the same name in superclasses to avoid confusion.

  • When a superclass redefines the same variable as a subclass, different values remain and are accessible.
  • The value returned depends on what casting has been done.

Methods

Overriding (instance, non-static methods only)

  • cannot reduce access (i.e. protected → private, not acceptable)
  • cannot broaden exception signature (can “drop” checked exceptions)
  • return type must be “covariant” (same or subtype as parent method)

Static Methods

  • Static methods can be “Hidden”
  • Equivalent to instance method overriding
  • Doesn’t override. Just hides. Original static method still can be called.
  • Can get very messy. DO NOT USE.

Nested classes

  • “inner class”: not static, defined at same level as a method
    • Requires an instance of the ‘outer’ class
    • Outer o = new Outer();
    • Inner i = o.new Inner();
    • i.myMethod();
  • “static nested class”: static, defined at same level as a method
    • Inner i = new Outer.Inner();
    • i.myMethod();
  • “local class”: used inside a method, given a class name
    • No access modifier, cannot be static, can access effectively final instance variables
  • “anonymous class”: used inside a method but without a class name
    • must extend class / implement interface
    • definition and instantiation in one step
    • AutoCloseable myThing = new AutoCloseable(){ void close(){…implementation…} };

Enums

  • a lists of values
  • cannot be extended
  • code must start with list
  • only a single instance of the Enum
  • can have constructor & methods
public enum Month {
	JAN(1), FEB(2), MAR(3);
	private int monthNo;
	private Month(int count){
		this.monthNo = count;
	}
	public int getMonthNo() {
		return this.monthNo;
	}
}

Abstract classes

  • cannot be instantiated directly
  • to be useful must be “extended” by a subclass
  • may contain abstract methods – ‘empty’ methods that MUST be overridden
  • abstract methods are not possible in non-abstract classes
  • abstract/final, abstract/private and abstract/static do not make sense (could not be overridden)

Interfaces

  • cannot be instantiated directly
  • to be useful must be “implemented” by a subclass
  • subclasses can implement several interfaces
  • all variables implicitly “public static final”
  • methods “public abstract” unless specified (not default access / package-private)
  • interfaces can extend other interfaces (but not classes)
  • can include variables: ‘final static’ added automatically if not already present
  • “default” methods can include method body, implicitly “public”
  • “static” methods also implicitly “public”: (InterfaceName.staticMethod(…) )
  • Can include private and private static methods – can only be called by default & static methods.

Subclasses of interfaces

  • cannot add checked exceptions
  • cannot make items “more private” than they are in the interface (can make them “more public”)