Object Orientation
Encapsulation
Do not expose class variables, instead of doing this, use setter and getter methods and keep class variables private.
public class Car { private int price; private int maxSpeed; public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } }
What is the advantage of previous usage, first of all flexibility. For example you have changed your mind, decide to keep max speed read only. So we can just remove setMaxSpeed method or change it to private for internal use.
Another advantage is validation, if user want to set negative value for car price, so you can add a validation in setPrice that is it.
Is-A and Has-A Relationship
So, Ferrari is a Car, Cow is an animal lets codify these statements.
Read the rest of this entry »