Skip to content

Instantly share code, notes, and snippets.

@cburgmer
Created October 4, 2011 17:36
Show Gist options
  • Save cburgmer/1262263 to your computer and use it in GitHub Desktop.
Save cburgmer/1262263 to your computer and use it in GitHub Desktop.
OOPExercise3
public class Area extends Measurement {
public Area(int value) {
super(value);
}
}
public class Length extends Measurement {
public Length(int value) {
super(value);
}
public Area multiply(Length length) {
return new Area(this.value * length.value);
}
public Length multiply(int scalar) {
return new Length(this.value * scalar);
}
public Length add(Length length) {
return new Length(this.value + length.value);
}
}
public abstract class Measurement {
public final int value;
public Measurement(int value) {
this.value = value;
}
public String toString() {
return "" + value;
}
}
public class Rectangle {
protected final Length height;
protected final Length breadth;
public Rectangle(Length height, Length breadth) {
this.height = height;
this.breadth = breadth;
}
public Length perimeter() {
return height.add(breadth).multiply(2);
}
public Area area() {
return height.multiply(breadth);
}
public String displayString() {
return "Rectangle(height=" + height + ", breadth=" + breadth +")";
}
}
import org.junit.Assert;
import org.junit.Test;
public class ShapeTests {
@Test
public void shouldHavePerimeter() {
Rectangle rectangle = new Rectangle(new Length(4), new Length(5));
Length perimeter = rectangle.perimeter();
Assert.assertEquals(18, perimeter.value);
}
@Test
public void shouldHaveArea() {
Length width = new Length(4);
Length height = new Length(5);
Rectangle rectangle = new Rectangle(width, height);
Area area = rectangle.area();
Assert.assertEquals(20, area.value);
}
@Test
public void squareShouldHavePerimeter(){
Square square = new Square(new Length(2));
Length perimeter = square.perimeter();
Assert.assertEquals(8, perimeter.value);
}
@Test
public void squareShouldHaveArea(){
Square square = new Square(new Length(2));
Area area = square.area();
Assert.assertEquals(4, area.value);
}
@Test
public void shouldDisplayRectangleDimensions(){
Rectangle rectangle = new Rectangle(new Length(10), new Length(12));
Assert.assertEquals("Rectangle(height=10, breadth=12)",rectangle.displayString());
}
@Test
public void shouldDisplaySquareDimensions(){
Square square = new Square(new Length(10));
Assert.assertEquals("Square(length=10)",square.displayString());
}
}
public class Square extends Rectangle {
public Square(Length length) {
super(length, length);
}
public String displayString(){
return "Square(length=" + height + ")";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment