In our real world we can have many objects all of the same kind. You can think of cars, computers or bicycles. There may be millions of bicycles all of them made with the same characteristics but still each bike represents a different object. In object-oriented terms it is said each bicycle among these million bikes is an instance of the class of object in this case the class Bicycle. A class can be seen as a blueprint which is going to specify the characteristics of the object we are modeling in our software (..of course using the Object-oriented paradigm!!)
We are ready to create our first software object and we are going to retake the Bicycle example. As I mentioned in OOP languages classes are the blueprints to specify the characteristics of an object and Java is an OOP language so let's model the object Bicycle using Java.
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" + cadence +
" speed:"+speed + " gear:"+gear);
}
}
Coming back to our Bicycle object, it is important to keep in mind that this object does not represents a complete application. The responsibility of creating and using new Bicycle objects belongs to some other class in our application.
Lets codify this class and start creating and using Bicycle objects:
class BicycleDemo {The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
No comments:
Post a Comment