Java作业,编程练习题,继承与多态
该类包括:
- 三个名为side1、side2、side3的double类型数据域表示这个三角形的三条边,它们的默认值是1.0
- 一个无参构造方法,创建一个默认的三角形
- 一个创建指定side1、side2、side3值的三角形的构造方法
- 所有三个数据域的访问器方法
- 一个名为getArea()的方法返回该三角形的面积
- 一个名为getPerimeter()方法返回该三角形的周长
- 一个名为toString()的方法返回该三角形的字符串描述。
画出Triangle类和GeometricObject类的UML图,并实现这些类。编写一个测试程序,提示用户输入三角形的三条边、颜色以及一个Boolean值表明该三角形是否填充。程序需要根据输入创建一个具有指定边的三角形,并设置color和filled属性。程序需要显示面积、周长、颜色以及表明是否填充的真或假值。
代码:
GeometricObject类:
public class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
public GeometricObject() {
dateCreated = new java.util.Date();
}
public GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public java.util.Date getDateCreated(){
return dateCreated;
}
public String toString() {
return "created on" + dateCreated + "\ncolor: " + color + " and filled: " + filled;
}
}
Triangle类:
public class Triangle extends GeometricObject {
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
public Triangle() {
}
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public Triangle(double side1, double side2, double side3, String color, boolean filled) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
setColor(color);
setFilled(filled);
}
public double getArea() {
double s = (side1 + side2 + side3)/2;
return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
}
public double getPerimeter() {
return side1+side2+side3;
}
public String toString() {
return "Triangle: side1= " + side1 + " side2 = " + side2 + " side3 = " + side3;
}
}
测试程序:
import java.util.Scanner;
public class HomeWork1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please input three side && color && judgment value: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
String color = new String();
color = input.next();
boolean filled = input.hasNext();
Triangle T1 = new Triangle(side1, side2, side3, color, filled);
System.out.println("此三角形的面积为:" + T1.getArea());
System.out.println("此三角形的周长为:" + T1.getPerimeter());
System.out.println("此三角形的颜色为:" + T1.getColor());
System.out.println("此三角形是否填充?" + T1.isFilled());
input.close();
}
}
在这里搞UML图可能人会没
运行结果: