Simple class-design in Java

WHEN I TRY TO LEARN a new subject I always thought the best way is to try to explain what I’ve learned to someone else. Therefore I’m continue my experience with Java here and try to xplain in steps what I have been doing and learning.

So let’s get to create an easy class with some basic content. We start with the skeleton of my ‘Car’ class.

public class Car {
  public Car(){
  }
}

We need to state what fields exist for our car, in other words what are the caracteristics of our car we see on all cars that exist.

public class Car {
  private int speed;  // current speed of our car
  private int passangers; // the number of passangers

  public Car(){
  }
}

If we want the passangers-variable to always be set to four when we create a new car we just place it within our constructor. We can also get values from the creator at this stage, we use this to set the speed.

public class Car {
  private int speed;  // current speed of our car
  private int passangers; // the number of passangers

  public Car(int speed){
    this.speed = speed;
    this.passangers = 4;
  }
}

AS YOU CAN SEE we use the keyword this to use the fields available to us within the class. Also noteworthy is that in our constructor we chose to call the incoming parameter for speed eventhough our field is called speed. This is no problems and we just use our this keyword to separate the one from the other.

Our fields was set to private, this means that only the class itself have access to the values stored within. Due to this we must create methods for getting and setting the values in some way. We call these methods getters and setters.

public class Car {
  private int speed;  // current speed of our car
  private int passangers; // the number of passangers

  public Car(int speed){
    this.speed = speed;
    this.passangers = 4;
  }

  public int getSpeed() {
    return this.speed;
  }

  public int getPassengers() {
    return this.passengers;
  }

  public void setSpeed(int speed) {
    this.speed = speed;
  }

  public void setPassengers(int passengers) {
    this.passengers = passengers;
  }

}

We now have the backbone of our class with getters and setters in place.

Leave a Reply

Your email address will not be published. Required fields are marked *