public class Rectangle {
private int x,y,width,height;
//생성자
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
//사각형 넓이 리턴
public int square() {
return width*height;
}
//사각형의 좌표와 넓이를 화면에 출력
void show() {
System.out.println("("+x+","+y+")에서 크기가 "+width+"x"+height+"인 사각형");
}
//매개변수로 받은 r이 현 사각형 안에 있으면 리턴
boolean contains(Rectangle r) {
if((x<r.x&&(r.x+r.width)<(x+width))&&(y<r.y&&(r.y+r.height)<(y+height))) {
return true;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Rectangle r = new Rectangle(2,2,8,7);
Rectangle s = new Rectangle(5,5,6,6);
Rectangle t = new Rectangle(1,1,10,10);
r.show();
System.out.println("s의 면적은 "+s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s을 포합합니다.");
}
}
결과
(2,2)에서 크기가 8x7인 사각형
s의 면적은 36
t는 r을 포함합니다.
'명품JAVA프로그래밍 > 4장 클래스와 객체' 카테고리의 다른 글
[명품JAVA프로그래밍] 4장 실습문제 6번 (0) | 2021.12.27 |
---|---|
[명품JAVA프로그래밍] 4장 실습문제 5번 (0) | 2021.12.27 |
[명품JAVA프로그래밍] 4장 실습문제 3번 (0) | 2021.12.27 |
[명품JAVA프로그래밍] 4장 실습문제 2번 (0) | 2021.12.27 |
[명품JAVA프로그래밍] 4장 실습문제 1번 (0) | 2021.12.27 |