글 작성자: 취업중인 피터팬
728x90
기본 환경
JDK : 1.8.0_261 버전
JRE : 1.8.0_261 버전
JAVA VERSION : 8 업데이트 261
Eclipse IDE VERSION : 2020-06버전

 

시나리오

Triangle 클래스을 만들어 밑변과 높이를 전달해 주고 삼격형의 높이를 구하는 클래스를 만들어라 


 

다음과 같은 결과가 나와야 합니다.
public class QuTriangle {
public static void main(String[] args) {
Triangle t = new Triangle();
t.init(10, 17); //밑변10, 높이17로 초기화
System.out.println("삼각형의 넓이 : " + t.getArea());
t.setBottom(50);//밑변 50으로 변경
t.setHeight(14);//높이 14로 변경
System.out.println("삼각형의 넓이 : " + t.getArea());
}
}

 

 

정답
package ex08Class;
class Triangle{
//맴버 변수
double Bottom;
double Height;
//밑변과 높이를 초기화 하는 맴버메소드
void init(double bottom, double height) {
this.Bottom = bottom;
this.Height = height;
}
//삼각형의 넓이를 구하는 맴버메소드
double getArea() {
double result = (Bottom * Height) / 2.0;
return result;
}
//밑변을 설정
void setBottom(double bottom) {
this.Bottom = bottom;
}
//높이를 설정
void setHeight(double height) {
this.Height = height;
}
}
public class QuTriangle {
public static void main(String[] args) {
Triangle t = new Triangle();
t.init(10, 17); //밑변10, 높이17로 초기화
System.out.println("삼각형의 넓이 : " + t.getArea());
t.setBottom(50);//밑변 50으로 변경
t.setHeight(14);//높이 14로 변경
System.out.println("삼각형의 넓이 : " + t.getArea());
}
}

 

사실 생성자를 써야 하지만 init()함수로 초기화 해주었습니다. 생성자를 사용하는 것이 더 좋은 코드입니다.