Dirty little secret: String was declared final, as in:
public final class String { . This means we can't
actually derive anything off it. If we try, we get:
Foo.java:1: cannot inherit from final java.lang.String
public class Foo extends String {
So let's look at another
example. Below is a basic position class from our Tron game:
public class Pos
{
private int r, c, d;
public Pos(int row, int col, int dir)
{
r = row; c = col; d = dir;
}
public void moveForward()
{
int[] dr = { -1, 0, 1, 0 };
int[] dc = { 0, 1, 0,-1 };
r += dr[d];
c += dc[d];
}
public void turnRight()
{
d = (d + 1)%4;
}
public void turnLeft()
{
d = (d + 3)%4;
}
public int getRow()
{
return r;
}
public int getCol()
{
return c;
}
public int getDir()
{
return d;
}
public String toString()
{
return "(" + r + "," + c + "," + d + ")";
}
public static void main(String[] args)
{
Pos p = new Pos(4,7,1);
System.out.println(p);
p.moveForward();
System.out.println(p);
}
}
What is we wanted to label our positions in some way? In this
case we could extend the position class, and add a label as a
string. Notice how we get all sorts of other stuff for free, and we
can use things like super.toString() in our own toString() to reuse
as much as possible.