This is 3.141592653589793
반지름이 5 인 원의 면적은 78.53981633974483
너비가 10 이고, 높이가 10 인 사각형의 면적은 100.0
너비가 10 이고, 높이가 10 인 삼각형의 면적은 50.0
File :Ch11Ex04
import kame.ch11.ex02.Circle;
import kame.ch11.ex02.Rectangle;
import kame.ch11.ex02.Shape;
import kame.ch11.ex02.Triangle;
public class Ch11Ex04 {
public static void polyMethod(Shape ref){
ref.area();
if ( ref instanceof Circle) {
Circle c=(Circle)ref;
System.out.println("반지름이 " + c.r + " 인 원의 면적은 " + c.res);
}
else if ( ref instanceof Rectangle) {
Rectangle r=(Rectangle)ref;
System.out.println("너비가 "+ r.w+" 이고, 높이가 "+ r.h+" 인 사각형의 면적은 " + r.res);
}
else if ( ref instanceof Triangle) {
Triangle t=(Triangle)ref;
System.out.println("너비가 "+ t.w+ " 이고, 높이가 "+ t.h+ " 인 삼각형의 면적은 " + t.res);
}
}
public static void main(String[] args) {
Shape c=new Circle();
Shape r=new Rectangle();
Shape t=new Triangle();
polyMethod(c);
polyMethod(r);
polyMethod(t);
}
}
File : Circle
package kame.ch11.ex02;
public class Circle extends Shape {
public int r=5;
public double area( ){
res=r*r*Math.PI;
System.out.println("This is "+ Math.PI );
return res;
}
}
File : Rectangle
package kame.ch11.ex02;
public class Rectangle extends Shape {
public int w=10;
public int h=10;
public double area( ){
res=w*h;
return res;
}
}
File : Shape
package kame.ch11.ex02;
public class Shape {
public double res=0;
public double area( ){
return res;
}
}
File :Triangle
package kame.ch11.ex02;
public class Triangle extends Shape {
public int w=10;
public int h=10;
public double area( ){
res=w*h*0.5;
return res;
}
}
댓글 없음:
댓글 쓰기