아래의 클래스 다이어그램을 참고하여 도형 관련 클래스들을 만드시오.


원-
package practice;
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return radius * radius * Math.PI;
}
@Override
public double perimeter() {
return radius * 2 * Math.PI;
}
public String toString() {
return "도형의 종류: 원, 둘레: " + perimeter() + "㎝" + ", 넓이: " + area() + "㎝";
}
}
사각형 -
package practice;
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
@Override
public double perimeter() {
return (width + height) * 2;
}
public String toString() {
return "도형의 종류: 사각형, 둘레: " + perimeter() + "㎝" + ", 넓이: " + area() + "㎝";
}
}
삼각형 -
package practice;
public class Triangle extends Shape {
private double side;
public Triangle(double side) {
this.side = side;
}
@Override
public double area() {
return Math.sqrt(3) * side * side / 4;
}
@Override
public double perimeter() {
return side * 3;
}
public String toString() {
return "도형의 종류: 삼각형, 둘레: " + perimeter() + "㎝" + ", 넓이: " + area() + "㎝";
}
}
package practice;
public class ShapeTest {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(1.0);
shapes[1] = new Triangle(2.0);
shapes[2] = new Rectangle(2.0,3.0);
for(Shape shape : shapes) {
System.out.println(shape);
}
}
}

'Java > 과제' 카테고리의 다른 글
chapter 08) 인터페이스example - Shape 클래스 변경하기 (0) | 2022.08.31 |
---|---|
chapter 07) 상속example - 은행 관련 클래스 확장하기 (0) | 2022.08.29 |
chapter 07) 상속example - Student 클래스 만들기 (0) | 2022.08.26 |
chapter06) 클래스 example - NewCar (0) | 2022.08.24 |
chapter06) 클래스 example - Car (0) | 2022.08.24 |