Skip to content

Commit b232d56

Browse files
ystrommMartin CarlssonErikSchierboom
authored andcommitted
add constructors exercise exercism#1864
add constructors exercise exercism#1864 Co-authored-by: Martin Carlsson <martin.carlsson@svt.se> Co-authored-by: Erik Schierboom <erik_schierboom@hotmail.com>
1 parent 2a62a64 commit b232d56

10 files changed

Lines changed: 522 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
Creating an instance of a _class_ is done by calling its [_constructor_][constructors] through the [`new` operator][new]. A constructor is a special type of method whose goal is to initialize a newly created instance. Constructors look like regular methods, but without a return type and with a name that matches the classes' name.
2+
3+
```java
4+
class Library {
5+
private int books;
6+
7+
public Library() {
8+
this.books = 10;
9+
}
10+
}
11+
12+
// This will call the constructor
13+
var library = new Library();
14+
```
15+
16+
Like regular methods, constructors can have parameters. Constructor parameters are usually stored as (private) [fields][fields] to be accessed later, or else used in some one-off calculation. Arguments can be passed to constructors just like passing arguments to regular methods.
17+
18+
```java
19+
class Building {
20+
private int numberOfStories;
21+
private int totalHeight;
22+
23+
public Building(int numberOfStories, double storyHeight) {
24+
this.numberOfStories = numberOfStories;
25+
this.totalHeight = numberOfStories * storyHeight;
26+
}
27+
}
28+
29+
// Call a constructor with two arguments
30+
var largeBuilding = new Building(55, 6.2)
31+
```
32+
33+
Specifying a constructor is optional. If no constructor is specified, a parameterless constructor is generated by the compiler:
34+
35+
```java
36+
class Elevator {
37+
}
38+
39+
// This will call the (empty) generated constructor
40+
var elevator = new Elevator();
41+
```
42+
43+
If fields have an initial value assigned to them, the compiler will output code in which the assignment is actually done inside the constructor. The following class declarations are thus equivalent (functionality-wise):
44+
45+
```java
46+
class UsingFieldInitialization {
47+
private int players = 5;
48+
}
49+
50+
class UsingConstructorInitialization {
51+
private int players;
52+
53+
public UsingConstructorInitialization() {
54+
players = 5;
55+
}
56+
}
57+
```
58+
59+
[constructors]: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
60+
[new]: https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
61+
[fields]: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
## 1. Creating a remote controlled car
2+
3+
- [Define a constructor][constructor-syntax] that has two `int` parameters.
4+
- Store the two parameters as [fields][fields] to access them from the classes' methods.
5+
6+
## 2. Creating a race track
7+
8+
- [Define a constructor][constructor-syntax] that has one `int` parameter.
9+
- Store the parameter as a [field][fields] to access it from the class' method.
10+
11+
## 3. Drive the car
12+
13+
- Add a [field][fields] to keep track of the distance driven.
14+
- Add the car's speed to the [field][fields] that keeps track of the distance driven.
15+
16+
## 4. Check for a drained battery
17+
18+
- Add a [field][fields] to keep track of the remaining battery charge percentage (starts at 100%).
19+
- Remove the car's battery drain from the [field][fields] to keep track of the battery charge.
20+
- Don't update the distance driven if the battery is drained.
21+
- Remember that if the battery charge is less than the battery drain percentage, it is considered drained.
22+
23+
## 5. Create the Nitro remote control car
24+
25+
- [Instantiate][instance-constructors] an instance of the `RemoteControlCar` with the correct arguments.
26+
27+
## 6. Check if a remote control car can finish a race
28+
29+
- Solving this is probably best done by [repeatedly driving the car][while].
30+
- Remember that the car has a method to retrieve the distance it has driven.
31+
- Consider what to do when the battery has been drained before reaching the finish line.
32+
33+
[constructor-syntax]: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
34+
[instance-constructors]: https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
35+
[while]: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
36+
[fields]: https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
In this exercise you'll be organizing races between various types of remote controlled cars. Each car has its own speed and battery drain characteristics.
2+
3+
Cars start with full (100%) batteries. Each time you drive the car using the remote control, it covers the car's speed in meters and decreases the remaining battery percentage by its battery drain.
4+
5+
If a car's battery is below its battery drain percentage, you can't drive the car anymore.
6+
7+
Each race track has its own distance. Cars are tested by checking if they can finish the track without running out of battery.
8+
9+
You have six tasks, each of which will work with remote controller car instances.
10+
11+
## 1. Creating a remote controlled car
12+
13+
Allow creating a remote controller car by defining a constructor for the `RemoteControlCar` class that takes the speed of the car in meters and the battery drain percentage as its two parameters (both of type `int`):
14+
15+
```java
16+
int speed = 5;
17+
int batteryDrain = 2;
18+
var car = new RemoteControlCar(speed, batteryDrain);
19+
```
20+
21+
## 2. Creating a race track
22+
23+
Allow creating a race track by defining a constructor for the `RaceTrack` class that takes the track's distance in meters as its sole parameter (which is of type `int`):
24+
25+
```java
26+
int distance = 800;
27+
var raceTrack = new RaceTrack(distance);
28+
```
29+
30+
## 3. Drive the car
31+
32+
Implement the `RemoteControlCar.drive()` method that updates the number of meters driven based on the car's speed. Also implement the `RemoteControlCar.distanceDriven()` method to return the number of meters driven by the car:
33+
34+
```java
35+
int speed = 5;
36+
int batteryDrain = 2;
37+
var car = new RemoteControlCar(speed, batteryDrain);
38+
car.drive();
39+
40+
car.distanceDriven();
41+
// => 5
42+
```
43+
44+
## 4. Check for a drained battery
45+
46+
Update the `RemoteControlCar.drive()` method to drain the battery based on the car's battery drain. Also implement the `RemoteControlCar.batteryDrained()` method that indicates if the battery is drained:
47+
48+
```java
49+
int speed = 5;
50+
int batteryDrain = 2;
51+
var car = new RemoteControlCar(speed, batteryDrain);
52+
car.drive();
53+
54+
car.batteryDrained();
55+
// => false
56+
```
57+
58+
## 5. Create the Nitro remote control car
59+
60+
The best-selling remote control car is the Nitro, which has a stunning top speed of 50 meters with a battery drain of 4%. Implement the (static) `RemoteControlCar.nitro()` method to return this type of car:
61+
62+
```java
63+
var car = RemoteControlCar.nitro();
64+
car.drive();
65+
car.distanceDriven();
66+
// => 50
67+
```
68+
69+
## 6. Check if a remote control car can finish a race
70+
71+
To finish a race, a car has to be able to drive the race's distance. This means not draining its battery before having crossed the finish line. Implement the `Race.carCanFinish()` method that takes a `RemoteControlCar` instance as its parameter and returns `true` if the car can finish the race; otherwise, return `false`:
72+
73+
```java
74+
int speed = 5;
75+
int batteryDrain = 2;
76+
var car = new RemoteControlCar(speed, batteryDrain);
77+
78+
int distance = 100;
79+
var race = new Race(distance);
80+
81+
race.carCanFinish(car);
82+
// => true
83+
```
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Creating an instance of a _class_ is done by calling its _constructor_ through the `new` operator. A constructor is a special type of method whose goal is to initialize a newly created instance. Constructors look like regular methods, but without a return type and with a name that matches the classes' name.
2+
3+
```java
4+
class Library {
5+
private int books;
6+
7+
public Library() {
8+
// Initialize the books field
9+
this.books = 10;
10+
}
11+
}
12+
13+
// This will call the constructor
14+
var library = new Library();
15+
```
16+
17+
Like regular methods, constructors can have parameters. Constructor parameters are usually stored as (private) fields to be accessed later, or else used in some one-off calculation. Arguments can be passed to constructors just like passing arguments to regular methods.
18+
19+
```java
20+
class Building {
21+
private int numberOfStories;
22+
private int totalHeight;
23+
24+
public Building(int numberOfStories, double storyHeight) {
25+
this.numberOfStories = numberOfStories;
26+
this.totalHeight = numberOfStories * storyHeight;
27+
}
28+
}
29+
30+
// Call a constructor with two arguments
31+
var largeBuilding = new Building(55, 6.2);
32+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"contributors": [
3+
{
4+
"github_username": "mirkoperillo",
5+
"exercism_username": "mirkoperillo"
6+
}
7+
],
8+
"authors": [
9+
{
10+
"github_username": "ystromm",
11+
"exercism_username": "ystromm"
12+
}
13+
]
14+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
## Learning objectives
2+
3+
- Know what classes are.
4+
- Know what encapsulation is.
5+
- Know what fields are.
6+
- Know how to create an object.
7+
- Know how to update state through methods.
8+
- Know about the `void` type.
9+
10+
## Out of scope
11+
12+
- Reference equality.
13+
- Constructors.
14+
- Interfaces.
15+
- Inheritance.
16+
- Finalizers.
17+
- Method overloading.
18+
19+
## Concepts
20+
21+
- `classes`: know what classes are; know what encapsulation is; know what fields are; know how to create an object; know how to update state through methods; know about the `void` type.
22+
23+
## Prerequisites
24+
25+
- `basics`: know how to define a basic class with basic methods.
26+
- `strings`: know how to do basic string interpolation.
27+
- `numbers`: know how to compare numbers.
28+
- `conditionals`: know how to do conditional logic.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class RemoteControlCar {
2+
private int speed;
3+
private int batteryDrain;
4+
private int distance = 0;
5+
private int battery = 100;
6+
7+
public RemoteControlCar(int speed, int batteryDrain) {
8+
this.speed = speed;
9+
this.batteryDrain = batteryDrain;
10+
}
11+
12+
public static RemoteControlCar nitro() {
13+
return new RemoteControlCar(50, 4);
14+
}
15+
16+
public boolean batteryDrained() {
17+
return battery == 0;
18+
}
19+
20+
public int distanceDriven() {
21+
return distance;
22+
}
23+
24+
public void drive() {
25+
if (battery > 0) {
26+
battery -= batteryDrain;
27+
distance += speed;
28+
}
29+
}
30+
}
31+
32+
class RaceTrack {
33+
private int distance;
34+
35+
RaceTrack(int distance) {
36+
this.distance = distance;
37+
}
38+
39+
public boolean carCanFinish(RemoteControlCar car) {
40+
while (!car.batteryDrained()) {
41+
car.drive();
42+
}
43+
return car.distanceDriven() >= this.distance;
44+
}
45+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.13"
11+
testImplementation "org.assertj:assertj-core:3.15.0"
12+
}
13+
14+
test {
15+
testLogging {
16+
exceptionFormat = 'short'
17+
showStandardStreams = true
18+
events = ["passed", "failed", "skipped"]
19+
}
20+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class RemoteControlCar {
2+
// TODO: define the constructor for the 'RemoteControlCar' class
3+
4+
public boolean batteryDrained() {
5+
throw new UnsupportedOperationException("Please implement the RemoteControlCar.batteryDrained() method");
6+
}
7+
8+
public int distanceDriven() {
9+
throw new UnsupportedOperationException("Please implement the RemoteControlCar.distanceDriven() method");
10+
}
11+
12+
public void drive() {
13+
throw new UnsupportedOperationException("Please implement the RemoteControlCar.drive() method");
14+
}
15+
16+
public static RemoteControlCar nitro() {
17+
throw new UnsupportedOperationException("Please implement the (static) RemoteControlCar.ntiro() method");
18+
}
19+
}
20+
21+
class RaceTrack {
22+
// TODO: define the constructor for the 'RaceTrack' class
23+
24+
public boolean carCanFinish(RemoteControlCar car) {
25+
throw new UnsupportedOperationException("Please implement the RaceTrack.carCanFinish() method");
26+
}
27+
}

0 commit comments

Comments
 (0)