利用介面和多型性計算幾何圖形的面積和周長並顯示
阿新 • • 發佈:2019-02-03
public interface Shape {
public double area(); //計算面積
public double perimeter(); //計算周長
}
class Square implements Shape {
double a; //邊長
public Square(double a) {
this.a = a;
}
public double area() {
return a*a;
}
public double perimeter() {
return 4*a;
}
}
class Rectangle implements Shape {
double a; //長或寬
double b; //長或寬
public Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
public double area() {
return a*b;
}
public double perimeter() {
return 2*(a+b);
}
}
class Circle implements Shape {
double radius; //半徑
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI*radius*radius;
}
public double perimeter() {
return 2*Math.PI*radius;
}
}
public class ShapeTest {
public static void print(Shape shape){
System.out.println(shape.getClass()+":"+"面積:"+shape.area());
System.out.println(shape.getClass()+":"+"周長:"+shape.perimeter());
}
public static void main(String[] args) {
Shape shape=new Rectangle(4,5);
print(shape);
shape=new Circle(4);
print(shape);
shape=new Square(5);
print(shape);
}
public double area(); //計算面積
public double perimeter(); //計算周長
}
class Square implements Shape {
double a; //邊長
public Square(double a) {
this.a = a;
}
public double area() {
return a*a;
}
public double perimeter() {
return 4*a;
}
}
class Rectangle implements Shape {
double a; //長或寬
double b; //長或寬
public Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
public double area() {
return a*b;
}
public double perimeter() {
return 2*(a+b);
}
}
class Circle implements Shape {
double radius; //半徑
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI*radius*radius;
}
public double perimeter() {
return 2*Math.PI*radius;
}
}
public class ShapeTest {
public static void print(Shape shape){
System.out.println(shape.getClass()+":"+"面積:"+shape.area());
System.out.println(shape.getClass()+":"+"周長:"+shape.perimeter());
}
public static void main(String[] args) {
Shape shape=new Rectangle(4,5);
print(shape);
shape=new Circle(4);
print(shape);
shape=new Square(5);
print(shape);
}
}