Java Constructors

New classes that you write need to have a constructor. Fortunately the form of these is always the same here.

 

package kareltherobot;

public class MileWalker extends ur_Robot
{
	public MileWalker(int Street, int Avenue, Direction direction, int numberOfBeepers)
	{	super(Street, Avenue, direction, numberOfBeepers);
	}

	public void moveMile() 
	{
		move();
		move();
		move();
		move();
		move();
		move();
		move();
		move();
	}
}

The constructor always has the same name as the class and is normally public. The rest is the same in every class you write. The meaning of super, by the way, is that the MileWalker when created must also execute the instructions defined for creating an ur_Robot, since the MileWalker inherits from ur_Robot. A MileWalker IS a ur_Robot (and more).

 

Note that we have also marked the moveMile method public here. In general you should probably do the same with all your methods when writing in real Java. In particular, if you give new versions for the built in commands like move or pickBeeper, you MUST mark them as public, since the versions define in ur_Robot are marked public.

In fact, it is a good idea to mark the class itself public. You can do this only if you put it in its own file, however. In Java you are encouraged to put one class in each file and normally to make the class public. The above belongs in a file named MileWalker.java.

You should also say which package the file belongs to with a package statement.

Finally note that in Java we normally avoid use of the underscore character in names. Class names are usually written beginning with an initial uppercase letter. If the name is a composed word like MileWalker, then subsequent words are also capitalized, such as the W in MileWalker. Method names are generally not capitalized, but have subsequent words capitalized: pickBeeper, for example. It is also a good idea not to abbreviate anything in a program. It is too easy to forget how you abbreviated it and then you spend a lot of time trying to keep consistent spelling. It also makes your programs easier to read and understand if everything is spelled out and you have chosen meaningful names. It takes a little longer to type out such names, but typing is not the reason programming can be hard.