Monday, May 26, 2008

Defining Classes and Subclasses

Classes form a hierarchy. For example, both letters and digits are characters that can be drawn on the computer screen. So, you can define

class ScreenCharacter {...}

and the subclasses

class Letter extends ScreenCharacter {...}

class Digits extends ScreenCharacter {...}

The keyword extends is used to distinguish the subclass (child class) and the superclass (parent class). If nothing is said about the superclass, then Java automatically considers it as a subclass of the Object class. So, with the above declarations you have constructed the following class hierarchy.The point is that all instance variables and methods that belong to the ScreenCharacter class are inherited by its subclasses so that they need not be defined again. For example, if at the higher level the ScreenCharacter class look like

class ScreenCharacter {

String name;

String fontname;

int fontsize;

int x, y;

void draw(Graphics g) {

g.setFont(new Font(fontname, Font.BOLD, fontsize));

g.drawString(name, x, y);

}

}

then the subclasses Letter and Digit do not have to introduce these instance variables and method again. By the way, if you are wondering why we chose the long name ScreenCharacter instead of Character, the reason is that the Java system already has a Character class built in (in the java.lang package) and we want to avoid name clashes.

The Letter class can be introduced as

class Letter extends ScreenCharacter {

String letterCase;

void setCase(String letterCase) {

this.letterCase = letterCase;

}

String getCase() {

return letterCase;

}

void toLowerCase() {

letterCase = "lowercase";

name = name.toLowerCase();

}

void toUpperCase() {

letterCase = "uppercase";

name = name.toUpperCase();

}

}

What distinguishes a letter from a character is that it is case sensitive: upper- and lowercase letters are possible. For digits case-sensitivity is not present. Above we have implemented the toUpperCase and toLowerCase methods in terms of methods with the same name in the String class.

No comments: