데이터과학자 - 강의/java
210629 Java - 인터페이스, 추상클래스, 상속, 다형성
vs질럿
2021. 6. 29. 17:37
클래스 다이어그램을 보고 클래스를 만들어 실행결과를 도출해라
============================================================================
Resize.java
public interface Resize {
void setResize(int size);
}
Shape.java
public abstract class Shape {
private int length;
private int width;
private String colors;
public Shape() {
super();
}
public Shape(int length, int width, String colors) {
super();
this.length = length;
this.width = width;
this.colors = colors;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public String getColors() {
return colors;
}
public void setColors(String colors) {
this.colors = colors;
}
public abstract double getArea();
}
Triangle.java
public class Triangle extends Shape implements Resize {
public Triangle() {
super();
}
public Triangle(int length, int width, String color) {
super(length, width, color);
}
@Override
public void setResize(int size) {
super.setLength(size + super.getLength());
}
@Override
public double getArea() {
double area = super.getLength() * (double)super.getWidth() / 2;
return area;
}
}
Rectangle.java
public class Rectangle extends Shape implements Resize {
public Rectangle() {
super();
}
public Rectangle(int length, int width, String color) {
super(length, width, color);
}
@Override
public void setResize(int size) {
super.setWidth(size + super.getWidth());
}
@Override
public double getArea() {
double area = super.getLength() * super.getWidth();
return area;
}
}
ShapeTest.java (main)
public class ShapeTest {
public static void main(String[] args) {
Shape[] sm = new Shape[6];
sm[0] = new Triangle(7, 5, "Blue");
sm[1] = new Rectangle(4, 6, "Blue");
sm[2] = new Triangle(6, 7, "Red");
sm[3] = new Rectangle(8, 3, "Red");
sm[4] = new Triangle(9, 8, "White");
sm[5] = new Rectangle(5, 7, "White");
System.out.println("기본정보");
System.out.println();
String shapeType = null;
for (int i = 0; i < sm.length; i++) {
Shape s = (Shape) sm[i];
if (s instanceof Triangle) {
shapeType = "Triagnle";
}
if (s instanceof Rectangle) {
shapeType = "Rectangle";
}
System.out.println(shapeType + "\t" + s.getArea() + "\t" + s.getColors());
}
System.out.println();
System.out.println("사이즈를 변경 후 정보");
System.out.println();
for (int i = 0; i < sm.length; i++) {
Shape s = (Shape) sm[i];
if (s instanceof Triangle) {
shapeType = "Triangle";
((Triangle) s).setResize(5);
}
if (s instanceof Rectangle) {
shapeType = "Rectangle";
((Rectangle) s).setResize(5);
}
System.out.println(shapeType + "\t" + s.getArea() + "\t" + s.getColors());
}
}
}