[Java] 도형 넓이 구현

Jeini·2022년 10월 31일
0

📌 Code list

목록 보기
22/55
post-thumbnail
class Shape {
	public int getArea() {
		return 0;
	}
	
	public String toString() {
		return "area: " + getArea();
	}
}
//원
class Circle extends Shape {
	private int radius;
	
	public Circle(int radius) {
		setRadius(radius);
	}
	
	@Override
	public int getArea() {
		return (int)(radius * radius * Math.PI);
	}
	
	@Override
	public String toString() {
		String info = "<Circle>\n";
		info += "radius: " + radius + "\n";
		info += super.toString();
		return info;
	}

	public int getRadius() {
		return radius;
	}

	public void setRadius(int radius) {
		this.radius = radius;
	}
	
}
// height와 width를 묶어서 한꺼번에 표현
class BasicShape extends Shape {
	private ShapeInfo info; // height + width 불러옴
	
	public BasicShape(ShapeInfo info) {
		setInfo(info);
	}

	public ShapeInfo getInfo() {
		return info;
	}

	public void setInfo(ShapeInfo info) {
		this.info = info;
	}
	
	@Override
	public String toString() {
		return info + "\n" + super.toString();
	}
}
//사각형
class Rectangle extends BasicShape {
	public Rectangle(ShapeInfo info) {
		super(info);
	}
	
	@Override
	public int getArea() {
		ShapeInfo info = getInfo();
		return info.getWidth() * info.getHeight();
	}
	
	@Override
	public String toString() {
		return "<Rectangle>\n" + super.toString();
	}
}
// 삼각형
class Triangle  extends BasicShape {
	public Triangle(ShapeInfo info) {
		super(info);
	}
	
	public int getArea() {
		ShapeInfo info = getInfo();
		return info.getHeight() * info.getWidth() / 2;
	}
	
	@Override
	public String toString() {
		return "<Triangle>\n" + super.toString();
	}
	
}
// 중복되는 height와 width 묶어줌 (has a)
class ShapeInfo {
	private int width;
	private int height;
	
	public ShapeInfo(int width, int height) {
		setHeight(height);
		setWidth(width);
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}
	
	public String toString() {
		return "width: " + width + "\n" + "height: " + height;
	}
	
}


public class ShapeAreaTest {

	public static void main(String[] args) {
		System.out.println(new Circle(8));
		ShapeInfo info = new ShapeInfo(10, 10);
		ShapeInfo info1 = new ShapeInfo(20, 20);
		System.out.println(new Rectangle(info));
		System.out.println(new Triangle(info1));
		
	}

}
profile
Fill in my own colorful colors🎨

0개의 댓글