본문 바로가기

Java/본격 Java 퀴즈 기초

[Java] 원과 원기둥 둘레와 넓기 구하기(상속 이용)

먼저 원에 대한 클래스를 만든다.

.

.

package Circle;
import java.math.*;

public class Circle {
	private double radius = 1;
	private String color = "red";
	Circle(){}
	Circle(double radius){
		this.radius = radius;
	}
	Circle(double radius, String color){
		this.radius = radius;
		this.color = color;
	}
	@Override
	public String toString() {
		return "Circle [radius=" + radius + ", color=" + color + "]";
	}
	public double getRadius() { return radius; }
	public void setRadius(double radius) { this.radius = radius; }
	public String getColor() { return color; }
	public void setColor(String color) { this.color = color; }
	public double getArea() {
		return radius * radius * Math.PI;
	}
}

.

.

그리고 원 클래스를 상속 받아 원기둥 클래스를 만든다.

.

.

package Circle;

public class Cylinder extends Circle {
	private double height = 1.0;
	Cylinder(){
		super();
	}
	Cylinder(double height){
		super();
		this.height = height;
	}
	Cylinder(double radius, double height){
		super(radius);
		this.height = height;
	}
	public double getHeight() { return height; }
	public void setHeight(double height) { this.height = height; }
	public double getVolume() {
		return super.getArea() * height;
	}
}

.

.

테스트해볼 메인 클래스를 작성한다.

.

.

package Circle;

public class TestCircle {

	public static void main(String[] args) {
		Cylinder c1 = new Cylinder();
		System.out.println(c1);
		System.out.println("c1 radius : " + c1.getRadius());
		System.out.println("c1 height : " + c1.getHeight());
		System.out.println("c1 base area : " + c1.getArea());
		System.out.println("c1 volume : " + c1.getVolume());
		System.out.println();
		
		Cylinder c2 = new Cylinder(10.0);
		System.out.println(c2);
		System.out.println("c2 radius : " + c2.getRadius());
		System.out.println("c2 height : " + c2.getHeight());
		System.out.println("c2 base area : " + c2.getArea());
		System.out.println("c2 volume : " + c2.getVolume());
		System.out.println();
		
		Cylinder c3 = new Cylinder(2.0, 10.0);
		System.out.println(c3);
		System.out.println("c3 radius : " + c3.getRadius());
		System.out.println("c3 height : " + c3.getHeight());
		System.out.println("c3 base area : " + c3.getArea());
		System.out.println("c3 volume : " + c3.getVolume());
		System.out.println();

	}

}

.

.

잘 나온다.

.

.

728x90
반응형