본문 바로가기
Language&FrameWorks/Java

도형(원,직사각형)의 넓이의 합을 구하는 문제

by 감마 2011. 5. 7.

package ch07.ex14;

abstract class Shape {

Point p;


Shape() {

this(new Point(0,0));

}


Shape(Point p) {

this.p = p;

}



abstract double calcArea();  // 도형의 면적을 계산해서 반환하는 메서드


Point getPosition() {

return p;

}


void setPosition(Point p) {

this.p = p;

}

}


class Point {

int x;

int y;


Point() {

this(0,0);

}


Point(int x, int y) {

this.x=x;

this.y=y;

}


public String toString() {

return "["+x+","+y+"]";

}

double calcArea() {

return x * y;

}

}


class Circle extends Shape{

double r;

Circle(double r){

this(new Point(), r);

}

Circle(Point p, double r){

super(p);

this.r = r;

}

double calcArea() {

return Math.PI * r * r;

}

}


class Rectangle extends Shape{

int width  = 0;

int height = 0;

Rectangle(int w, int h){

this(new Point(0,0),w,h);

}

Rectangle(Point p,int w, int h){

super(p);

this.width = w;

this.height = h;

}

boolean isSquare(){

boolean b = false;

if(this.width == this.height) b =true;

return b;

}

double calcArea() {

// TODO Auto-generated method stub

return width * height;

}

}




package ch07.ex14;


class Exercise7_23 

{

/*

(1) sumArea메서드를 작성하시오.

*/

static double  sumArea(Shape[] s){

double sSum = 0;

for(Shape aS:s){

sSum += aS.calcArea();

}

return sSum;

}


public static void main(String[] args) 

{

Shape[] arr = {new Circle(5.0), new Rectangle(3,4), new Circle(1)};


System.out.println("면적의 합:"+sumArea(arr));

}

}



댓글