Create a Car class with constructor - Java Object Oriented Design

Java examples for Object Oriented Design:Constructor

Introduction

The car class has three field:

  • status is a String
  • speed is an int
  • temperature is a float

Demo Code

class Car {// w ww .ja  v  a  2  s .  c om
  String status;
  int speed;
  float temperature;

  Car(String inStatus, int inSpeed, float inTemperature) {
    status = inStatus;
    speed = inSpeed;
    temperature = inTemperature;
  }
  void checkTemperature() {
    if (temperature < -80) {
      status = "returning home";
      speed = 5;
    }
  }
  void showAttributes() {
    System.out.println("Status: " + status);
    System.out.println("Speed: " + speed);
    System.out.println("Temperature: " + temperature);
  }
}

public class Main {
  public static void main(String[] arguments) {
    Car spirit = new Car("exploring", 2, -80);
    spirit.showAttributes();
    System.out.println("Increasing speed to 3.");
    spirit.speed = 3;
    spirit.showAttributes();
    System.out.println("Changing temperature to -100.");
    spirit.temperature = -100;
    spirit.showAttributes();
    System.out.println("Checking the temperature.");
    spirit.checkTemperature();
    spirit.showAttributes();
  }
}

Related Tutorials