Java Intermediate: Lesson 1 - class

Classes are a very important structure in object oriented programming. They can be considered like templates or set of rules which determine what an instance can do and how it can be. Instance is an object which is created through the new keyword. For example:

Example code:

Where ferrari is the instance of Car and Car is a class as shown in the example code bellow.

Example code:

Speed and color are the attributes of the car which store the state of instances. We will cover static attributes and methods as well which are not connected with instances. As it can be seen from the example code above there are setColor and setSpeed methods as well as getColor and getSpeed methods, this methods allow the access of the attributes of Car class from other classes. We will cover further more this topic when we will talk about access modifiers.

Except setters and getters classes may contain other methods which have different logic, like the accelerate method in the example shown above.

Considering a scenario where we have two cars, a Ferrari and a Lamborgini raceing with each other. Ferrari has a constant acceleration of 20 km/h until it reaches 100 km/h than it accelerates with 10 km/h until it reaches the top speed of 300 km/h while Lamborgini has a constant acceleration of 10 km/h until it reaches 100 km/h than it accelerates with 15 km/h until it reaches the top speed of 300 km/h. Which one of the cars will win the race if the race lasts for 5 km?

Solution is shown bellow.

Example code:

As seen from the example code above we have two instances of the Car class, ferrari and lamborgini. We call the accelerate method with different values so we change the value of speed attribute differently.

In the figure 1 bellow is shown the execution of the above code.

Figure 1: Execution of race application


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game