I just wrote about what a class is, in basic terms for those beginning on the CS106A course at Stanford on iTunes U. The next item I want to cover is what a method is.
What is a Method?>
Java allows you to create methods. In simple and beginner terms (meaning those working on programming with Karel), a method is a set of instructions that can be called on by name to execute. In a few of my previous posts I have already written about methods although I haven’t taken the time to explain exactly what a method is.
With Karel, the statements move(), turnLeft(), pickBeeper() and putBeeper() are all methods. We don’t see what a method is when we invoke these though because the methods are kept in the Karel blueprint at Stanford (which is covered in the link to what is a class above).
As Karel is limited to just these four methods/commands, he is quite limited. What Java allows us to do is define more methods that can be invoked. A common example used is a turnRight() command. When you invoke that statement, Karel doesn’t understand turnRight and would simply crash the program.
Instead, we need to define turnRight() as a method that can be invoked. To do this we add the following to our code just after the run block of code (the closing curly brace for the run method) but before the end curly brace of the class.
private void turnRight() {
turnLeft();
turnLeft();
turnLeft();
}
The above example of code is a method. Each time the turnRight() statement is executed, the programs runs this block of code which includes three turnLeft() statements.
You might have noticed that the turnRight() method is defined as being private whereas in sample code the run method was public. The difference is that the run method can be invoked by another class whereas the turnRight method can only be invoked from within the class it is written… ie, it is kept private.
At a later date you might want to make more public methods, but for examples in Karel you will typically stay private with all methods except the run method.
By using private methods, you are encapsulating the code which means that those outside of the class do not need to know how the innards work. This makes programs safer to work with meaning that you hide some of the complexities in the code. An example could be how your car engine works… you really don’t need to know all the inner workings of a combustion engine to drive a car… that information is “encapsulated” under the hood. Programs have lots of inner workings and when you encapsulate those and make those methods private, it makes it easier to work with, especially when programming with others working on the same project.
Leave a Reply
You must be logged in to post a comment.