A class in Java can be thought of as a blueprint. If using Karel the Robot as an example, each time we “extend Karel” we are getting a copy of Karel the robot to utilise. The blueprint specifies exactly what Karel can do out of the box. In terms of Karel, the blueprint is held at Stanford and we are not able to modify him. Every person who takes the iTunes U CS106A course takes a copy of Karel each time the program runs. The reason we cannot modify the blueprint is that changes we make would likely break everyone elses programs.
So what we do is become a subclass of Karel… ie, we “extend Karel” which means that our programs make an exact copy. When I use the word subclass, this is the opposite of superclass which is what Karel is to our own implementation. This doesn’t mean that ours is on a lower level… in fact, it could be said that we have more power being a sub-class because we get a copy of Karel and can enhance him with a turnRight() private method. So, our copy of Karel can do more than the blueprint specifies.
How to Create a Karel Subclass
Creating a class of Karel is quite simple. Our code needs a few things for it to work though. The first important line is the import which lets the program know where the blueprint is stored. In the case of Karel, this is held at Stanford at the location on line 1 of the code:
import stanford.karel.*;
public class MyEnhancedVersionOfKarel extends Karel {
public void run() {
turnRight();
}
private void turnRight() {
turnLeft();
turnLeft();
turnLeft();
}
}
So, in line 1 we have specified where the blueprint for Karel is stored. In line 3, we are creating a new class called MyEnhancedVersionOfKarel. As we are making a copy, we need to extend Karel. Remember that the import on line 1 understands what Karel is and when we extend Karel, we are becoming a subclass.
With Karel being for beginners, Stanford has helped out a little by creating a run method which is required to run Karel programs. In here, we have invoked a turnRight() method. By default, Karel does not understand this, but because we are a subclass of Karel, we can define this extra method. This is done on lines 8 to 12. This now means that MyEnhancedVersionOfKarel is now more enhanced than the standard Karel.
To give another brief overview, a subclass (in this case MyEnhanced…..) calls on the Karel blueprint. Note that there is extra code that is required. First, you need an import so that you know where to get the blueprint. You then need the public class definition which is the 3rd line and closes at line 14. This part is all standard code required for each class you make.
In between that you then need your public and private methods so that your program can be run and so that the class can be enhanced to do more than it was designed to do.
Note that lines 8 to 12 of the code are classed as a method. I cover what a method is over here.
Leave a Reply
You must be logged in to post a comment.