Defining classes

A class is a template for creating objects. The classes String and Stack are in the Java API; here we will see how to create our own classes.

A class usually looks like this:

class ClassName
{
    private type1 instVar1;
    private type2 instVar2;
    private static classVar;

    public ClassName ( type1 p1, type2 p2 )
    {
        instVar1 = p1;
	instVar2 = p2;
    }

    public type getInstVar1() 
    { 
  	return instVar1;
    }

    public void methName ( type3 p3, type4 p4)
    {
       ...
    }
}    

Notes

  1. Variables can be

    It's usual to make variables private, and where appropriate to provide "accessor methods".

  2. Methods can be similarly qualified. It's usual to declare as private "helper" methods which are specialised to the class, and public methods which form part of the objects interface.
  3. The constructor is called to initialise an object when it is created. Typically, there is a constructor which takes parameters which are used to initialise the instance variables. There might also be a constructor taking no parameters; it creates an object with default values in the instance variables.
  4. Class variables are shared by the whole class; declared with static.
  5. Class methods do not work on an implicit "this" object of the class; declared with static.

Examples

Look at Time.java and Appointment.java.

Look at Fractions.java (illustrates static methods, and immutable objects)

Objects created from the Time and Appointment classes are mutable. Fraction objects are immutable (there are no methods which change a Fraction once it is created). Later, there is an exercise to rewrite the Fraction class to get mutable fractions. Both ways are possible. It's a matter of taste/style.

 

© 2001 Mark Ryan and Alan Sexton