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)
{
...
}
}
It's usual to make variables private, and where appropriate to provide "accessor methods".
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