Designing a Class
Estimated time to read: 2 minutes
Example Class¶
Suppose we are building a system that is going to model a traffic system
- We need a way to represent each car in the code
- We will need to know whether a car's engine is running and how much gas it has
- We will need to set each car's speed and prevent its speed from being greater than the speed limit
- We will also need to retrieve the current speed
UML: Car Class¶
Class Name Attributes Methods | Car | | :--------------------: | | - speed: Integer | | - gasoline: Integer | | - engineState: Integer | | ------------ | | + setSpeed() | | +getSpeed() |
The setSpeed() method will include code to prevent the speed from being set above the maximum speed limit. This is not full example of the class.
The Method Signatures¶
We defined two methods for Car: setSpeed()
and getSpeed()
setSpeed¶
setSpeed()
will assign a new speed to a car. For this to work, we have to say what the new speed is. We do that in the signature:
setSpeed(int newSpeed)
newSpeed
is the name of the variable thatsetSpeed()
will useint
states thatnewSpeed
will be an integer primitive
getSpeed¶
Car's getSpeed()
method can tell us how fast a particular car is going. When designing this method, we can specify the data type that the method will return/
int getSpeed()
- This states that
getSpeed()
returns an int.
Note
Not all methods need to return a value. They would have a return type of void, which means that it would return nothing.
JavaBeans (The what now? 🤔)¶
Getters and Setters in Java are known as JavaBeans and their properties of a bean.
What makes it a property is not the presence of the attributes, but the presence of methods that follow a specific naming convention.
- setX, taking some type and returning a void.
- getX, taking no arguments and returning a type
The overall Bean specification includes such things as index properties et al. See 109 - JavaBeans for more info. Tools are available to generate these Bean properties. Or you can do it by hand... like I do 😅
Code¶
package io.entityfour.codebook;
public class Car {
private int speed;
private int gas;
private boolean engineState;
public int getSpeed(){
return speed; // Referring to the return 'speed'. There is no local value, so it provides an implied '*this*', which is a reference to the attributes of the instance.
}
public void setSpeed(int speed){
this.speed = speed; // Since `speed = speed` would be hide the value from the method signature, we have to create an explicit reference using '*this.*'
// If instead the argument variables was a different name, you could do something like speed = NewSpeed;
}
}
In the above, the field 'speed' is a Bean property.