Lesson 1.6a -
A Student Class Design When designing a class, we typically have the following sections that make up that class:
Let's look at each section in depth: Instance Variables The instance variables consist of whatever data this class needs to maintain. We declare these variables just like regular variables, with one exception - we put the keyword private in front of them. For example, in the student class, we will maintain a student's name and three test scores, so we declare the following as instance variables:
So what does the keyword private do? By making instance variables private, we protect their values from outside manipulation. It also means that any attempt to use those variables outside of this file will meet with an undeclared identifier error. In other words, these variables are unknown outside this code (the opposite of private is public, but we will not use that keyword). Constructors A constructor is a method whose purpose is to instanciate or construct a new object. It is essentially a means to declare an object in a way similar to the way we declare variables, but involves more detail. Recall that when we declared a new robot object in Karel J. Robot, we had to give the robot a name and some initial information (coordinates, direction and number of beepers). That statement used a Robot constructor. In our example, we will construct a Student. This requires giving the student a name as well as values for the three test scores. There are three types of constructors:
See the file Student.java at this time to see how constructors are implemented in the Student class. Methods The methods of a class give the programmer functions that can be performed on and by the object. Recall that in Karel J. Robot we created methods to give the robot new skills to perform specific tasks. It is the same here, only more abstract. As with constructors, there are several types of methods:
See the file Student.java at this time to see how methods are implemented in the Student class. |
|||||||||||
© DanShuster.com