写一个程序,建一个三角形的类,一个长方形的类,他们都继承多边形类,都要实现接口,包括计算三角形和长方形的周长以及他们的周长差(写函数)

解决方案 »

  1.   

    public class Test {
    public static void main(String[] args) {
    int a = 0, b = 0, c = 0;
    Rectangle r=new Rectangle(a, b);
    System.out.println(r.circum());
    Triangle t=new Triangle(a, b, c);
    System.out.println(t.circum());
    System.out.println(r.circum()-t.circum());
    }
    }
    interface Polygon {
    public double circum();
    }
    class Rectangle implements Polygon {
    private double x, y;
    Rectangle(double x, double y) {
    this.x = x;
    this.y = y;
    }
    public double circum() {
    return 2 * (x + y);
    }
    }
    class Triangle implements Polygon {
    private double x, y, z;
    Triangle(double x, double y, double z) {
    this.x = x;
    this.y = y;
    this.z = z;
    }
    public double circum() {
    return x + y + z;
    }
    }
      

  2.   

    ========Interface=========
    package alex.interfaces;public interface polygon {
    /**
     * 计算多边形周长
     * @return
     */
    public double calculateGirth();

    }
    ================Class===============
    package alex.graphic;import alex.interfaces.polygon;public abstract class abstractPolygon implements polygon { public abstract double calculateGirth();

    /**
     * 计算两个多边形的周长差
     * @param obj
     * @return
     */
    public abstract double calculateGirthDiffrence(abstractPolygon obj);}
    package alex.graphic;public class Rectangle extends abstractPolygon { private double width,height;

    public Rectangle(){
    this.width = 0;
    this.height = 0;
    }

    public Rectangle(double w, double h){
    this.width = w;
    this.height = h;
    }

    public double calculateGirth() {
    return (this.width + this.height)*2;
    } public double calculateGirthDiffrence(abstractPolygon obj) {
    return this.calculateGirth() - obj.calculateGirth();
    }}package alex.graphic;public class Triangle extends abstractPolygon { private double x1,x2,x3;

    public Triangle(){
    this.x1 = 0;
    this.x2 = 0;
    this.x3 = 0;
    }

    public Triangle(double line1, double line2, double line3){
    this.x1 = line1;
    this.x2 = line2;
    this.x3 = line3;
    }

    public double calculateGirth() {
    return x1+x2+x3;
    } public double calculateGirthDiffrence(abstractPolygon obj) {
    return this.calculateGirth() - obj.calculateGirth();
    }}package alex.graphic;public class test {
    public static void main(String[] args){
    Rectangle r = new Rectangle(20,10);
    Triangle t = new Triangle(3,4,5);
    System.out.println("矩形周长="+r.calculateGirth());
    System.out.println("三角形周长="+t.calculateGirth());
    System.out.println("矩形-三角形周长差="+r.calculateGirthDiffrence(t));
    }
    }