classes and objects code added (#6173)

* classes and objects code added

* Car class and test added

* fixes and enhancements

* code moved to core-java-lang
This commit is contained in:
enpy 2019-01-22 17:18:11 +01:00 committed by maibin
parent 34907bfb0b
commit 5bbc85c6c1
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.baeldung.objects;
public class Car {
private String type;
private String model;
private String color;
private int speed;
public Car(String type, String model, String color) {
this.type = type;
this.model = model;
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSpeed() {
return speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
}
return this.speed;
}
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement;
} else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
@Override
public String toString() {
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.objects;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CarUnitTest {
private Car car;
@Before
public void setUp() throws Exception {
car = new Car("Ford", "Focus", "red");
}
@Test
public final void when_speedIncreased_then_verifySpeed() {
car.increaseSpeed(30);
assertEquals(30, car.getSpeed());
car.increaseSpeed(20);
assertEquals(50, car.getSpeed());
}
@Test
public final void when_speedDecreased_then_verifySpeed() {
car.increaseSpeed(50);
assertEquals(50, car.getSpeed());
car.decreaseSpeed(30);
assertEquals(20, car.getSpeed());
car.decreaseSpeed(20);
assertEquals(0, car.getSpeed());
}
}