Java summary: Classes

1. Package (optional)

   package package-name; // defines package to which this file belongs

2. Imports

Import all external classes you want to use.

import java.awt.Color; // Import one class (Color) of the java.awt package
import java.awt.event.* // Import all classes

3. Class Definition


[visibility][abstract] class class-name [extends parent-class] [implements interface-name...] { class-body }

visibility The default visibility is package visibility -- class is accessible to everyone in package
public -- can be used by everyone.
private -- visible only in this class.
protected -- visible in this class and all subclasses.??
abstract abstract class
parent-class This is the name of the parent class of this class (only one). The default parent class in java is Object.
interface-name For each interface that is implemented: this class must define all methods of the interface
class-body consists of attributes and methods

Class Types

concrete class All methods are concrete, have an implementation. Only these can be instantiated to create an object.
abstract class Got some abstract (non-implemented) methods. Should be overridden by child class to create a concrete class.
interface class No attributes or implemented methods (pure abstract class). Use keyword interface in definition.

An inner-class or nested class is defined in another class, as opposed to top-level classes. Can only be used inside that class. Can access all members of the outer class! As for example by an event listener.

4. Objects


Variable Node myNode; A reference to an object, null if empty.
Creation myNode = new Node(); A class in instantiated and the object is created by calling the constructor method.
Deletion -
Objects are automatically deleted when it has no more references (= garbage collection).
Passing objects as arguments
Do(myNode);
Always by reference.
Returning objects
return myNode;
Returns a reference.

Special Variables

final Constant, eg final int MAX_PAGES = 32;
static Class-level variable, only one value per class. Eg object counter, Class.sCounter++;
super Reference to the parent class, eg. super.Draw();
this Self-reference, eg. when returning a reference to yourself.

Object Operators

object.f Member (attribute or method) of object or class.
x == y Comparison, true if x and y refer to the same object, otherwise false (even if values of the objects are the same).
x != y As above for inequality.
comparison Compare object values with .equals() or .compareTo()
x = y Assignment copies the reference, not the object. Both variables refer to the same object. Clone the object to make a copy.
x instanceof co true if the object x is an instance of class co, or is an instance of the class of co.