这个JAVA怎么创建类

img


面向对象基础,主函数怎么调用其他类的方法,(不确定描述的对不对,抱歉<(_ _)>)

  • 先定义一个 三角形类,里面有三个边长的 成员属性,新加 setAll 方法设置三边【里面校验三边是否能组成三角形】, 新加 print 方法打印三条边
  • 主函数 通过 new 来创建 三角形类的实例 t ,通过 t 来调用 setAll 和 print 方法即可
  • 参考如下:
/**
 * @author huazie
 * @version 2.0.0
 * @since 2.0.0
 */
public class Triangle {

    private double side1;

    private double side2;

    private double side3;

    public void setAll(double side1, double side2, double side3) throws Exception{
        if (side1 < 0 || side2 < 0 || side3 < 0) {
            throw new Exception("边长必须为正数");
        }

        if (side1 + side2 < side3 || side1 + side3 < side2 || side2 + side3 < side1) {
            throw new Exception("三条边长必须能组合成三角形(三角形任意两边和大于第三边)");
        }
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public void print() {
        if (side1 > 0 && side2 > 0 && side3 > 0)
            System.out.print("三角形三边长分别为 " + side1 + "," + side2 + "," + side3);
    }

    public static void main(String[] args) throws Exception {
        Triangle t = new Triangle();
        t.setAll(3.0, 4.0, 5.0);
        t.print();
    }
}

创建三角形类

public class triangle {
    private double a;
    private double b;
    private double c;

    public triangle(double a, double b, double c) {
        if (a <= 0 || b <= 0 || c <= 0) {
            throw new illegalargumentexception("triangle side length should be positive");
        }
        if (a + b <= c || a + c <= b || b + c <= a) {
            throw new illegalargumentexception("not a triangle");
        }
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public void seta(double a) {
        if (a <= 0) {
            throw new illegalargumentexception("triangle side length should be positive");
        }
        if (a + b <= c || a + c <= b || b + c <= a) {
            throw new illegalargumentexception("not a triangle");
        }
        this.a = a;
    }

    public void setb(double b) {
        if (b <= 0) {
            throw new illegalargumentexception("triangle side length should be positive");
        }
        if (a + b <= c || a + c <= b || b + c <= a) {
            throw new illegalargumentexception("not a triangle");
        }
        this.b = b;
    }

    public void setc(double c) {
        if (c <= 0) {
            throw new illegalargumentexception("triangle side length should be positive");
        }
        if (a + b <= c || a + c <= b || b + c <= a) {
            throw new illegalargumentexception("not a triangle");
        }
        this.c = c;
    }

    public void printsides() {
        system.out.println("triangle sides: " + a + ", " + b + ", " + c);
    }
}


主函数调用例

public class main {
    public static void main(string[] args) {
        triangle triangle = new triangle(3, 4, 5);
        triangle.printsides();
        triangle.seta(2);
        triangle.printsides();
    }
}