Please follow me here!

Friday, December 14, 2012

JAVA Program: Car Class

Hello, people.

Sorry if I'm late with my Bloggers, but at least I know for sure that I need to upload one!

Anyway, let me show you one of the initial exercises I had in my JAVA Programming classes for creating classes instead of inputting those already from loaded packages.

There is no description of this, unfortunately, but this exercise comes from two JAVA files because the Car class is in a class file of its own.

Here it is:

public class Car
{
    private int yearModel;
    private String make;
    private int speed;

    public Car(int modelAndYear, String manufacturer)
    {
        yearModel = modelAndYear;
        make = manufacturer;
        speed = 0;
    }

    public void accelerate()
    {
        speed += 5;
    }

    public void brake()
    { 
        speed -= 5;
    }

    public int getYearModel()
    {
        return yearModel;
    }

    public String getMake()
    {
        return make;
    }

    public int getSpeed()
    {
       return speed;
    }

}

Below is the demonstration code for the Car class. In this case, the created car accelerates five times and have its speed displayed, then decelerates five times with its speed displayed. To make this simple, two for loops were used.

public class CarClassProgram
{
    public static void main(String[] args)
    {
        Car car1 = new Car(87, "Chevrolet");
       
        for (int x = 0; x < 5; x++)
        {
            car1.accelerate();
            System.out.println(car1.getSpeed());
        }
       
        for (int y = 0; y < 5; y++)
        {
            car1.brake();
            System.out.println(car1.getSpeed());
        }
    }
}


Well, I hope you've enjoyed checking this out! Later!

Google+ Followers

Popular Posts by Gregory