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 »

Comments

Java Basics

An introduction to Java programming languages. This post is intended to people who already know Java language but not sure about limits of what they can do and they cant such as which identifiers are valid which are not valid. An array can be defined in how many different ways ? Variables in interfaces. Enum definitions. Naming rules.

Read the rest of this entry »

Comments off