[상속-8] 오버라이딩-2 / 연습문제

seratpfk·2022년 8월 1일
0

JAVA

목록 보기
59/96

Shape클래스 (메인메소드 없음)

	private String type;  // 도형의 종류
	public Shape(String type) {
		super();
		this.type = type;
	}
	public double getArea() {
		return 0;
	}
	public void info() {
		System.out.println("도형의 종류 : " + type);
	}

Circle클래스 (메인메소드 없음)

public class Circle extends Shape {
	private double radius;
	public Circle(String type, double radius) {
		super(type);
		this.radius = radius;
	}
	@Override
	public double getArea() {
		return Math.PI * Math.pow(radius, 2);
	}
	@Override
	public void info() {
		super.info();
		System.out.println("반지름 : " + radius);
		System.out.println("넓이 : " + getArea());
	}
}

Main클래스 (메인메소드 설정)

	public static void main(String[] args) {
		Circle circle = new Circle("도넛", 7.5);
		circle.info();
	}

출력:
도형의 종류 : 도넛
반지름 : 7.5
넓이 : 176.71458676442586

연습문제

  • 너비, 높이가 서로 다른 직사각형(Rectangle)
  • 너비, 높이가 서로 같은 정사각형(Square)
  • 각각의 getArea(), info() 만들어 호출하기

Rectangle클래스 (메인메소드 없음)

public class Rectangle extends Shape {
	private double width;
	private double height;
	public Rectangle(String type, double width, double height) {
		super(type);
		this.width = width;
		this.height = height;
	}
	@Override
	public double getArea() {
		return width * height;
	}
	@Override
	public void info() {
		super.info();
		System.out.println("너비 : " + width + "높이 : " + height);
		System.out.println("넓이 : " + getArea());
	}
}

Square클래스 (메인메소드 없음)

public class Square extends Rectangle {
	public Square(String type, double width, double height) {
		super(type, width, height);
	}
}
  • 필드가 없을 때 생성 메소드: source -> Generate Constructor from Superclass...
public class Square extends Rectangle {
	public Square(String type, double width) {
		super(type, width, width);
	}
}
  • 정사각형이기 때문에 width와 height의 값이 같아서 width로 수정.

출력:
도형의 종류 : 사각형
너비 : 3.0높이 : 4.0
넓이 : 12.0
도형의 종류 : 정사각형
너비 : 5.0높이 : 5.0
넓이 : 25.0

0개의 댓글