Skip to content

Commit 5bbc85c

Browse files
enpy303maibin
authored andcommitted
classes and objects code added (eugenp#6173)
* classes and objects code added * Car class and test added * fixes and enhancements * code moved to core-java-lang
1 parent 34907bf commit 5bbc85c

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.objects;
2+
3+
public class Car {
4+
5+
private String type;
6+
private String model;
7+
private String color;
8+
private int speed;
9+
10+
public Car(String type, String model, String color) {
11+
this.type = type;
12+
this.model = model;
13+
this.color = color;
14+
}
15+
16+
public String getColor() {
17+
return color;
18+
}
19+
20+
public void setColor(String color) {
21+
this.color = color;
22+
}
23+
24+
public int getSpeed() {
25+
return speed;
26+
}
27+
28+
public int increaseSpeed(int increment) {
29+
if (increment > 0) {
30+
this.speed += increment;
31+
} else {
32+
System.out.println("Increment can't be negative.");
33+
}
34+
return this.speed;
35+
}
36+
37+
public int decreaseSpeed(int decrement) {
38+
if (decrement > 0 && decrement <= this.speed) {
39+
this.speed -= decrement;
40+
} else {
41+
System.out.println("Decrement can't be negative or greater than current speed.");
42+
}
43+
return this.speed;
44+
}
45+
46+
@Override
47+
public String toString() {
48+
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
49+
}
50+
51+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.objects;
2+
3+
import static org.junit.Assert.*;
4+
5+
import org.junit.Before;
6+
import org.junit.Test;
7+
8+
public class CarUnitTest {
9+
10+
private Car car;
11+
12+
@Before
13+
public void setUp() throws Exception {
14+
car = new Car("Ford", "Focus", "red");
15+
}
16+
17+
@Test
18+
public final void when_speedIncreased_then_verifySpeed() {
19+
car.increaseSpeed(30);
20+
assertEquals(30, car.getSpeed());
21+
22+
car.increaseSpeed(20);
23+
assertEquals(50, car.getSpeed());
24+
}
25+
26+
@Test
27+
public final void when_speedDecreased_then_verifySpeed() {
28+
car.increaseSpeed(50);
29+
assertEquals(50, car.getSpeed());
30+
31+
car.decreaseSpeed(30);
32+
assertEquals(20, car.getSpeed());
33+
34+
car.decreaseSpeed(20);
35+
assertEquals(0, car.getSpeed());
36+
}
37+
38+
}

0 commit comments

Comments
 (0)