(1)使用继承机制,分别设计实现抽象类 图形类,子类类圆形类、正方形类、长方形类,要求: ①抽象类图形类中有属性包括画笔颜色(String类型)、图形是否填充(boolean类型:true表示填充,false表示不填充), 有方法获取图形面积、获取图形周长等; ②使用构造方法为其属性赋初值; ③在每个子类中都重写toString()方法,返回所有属性的信息; ④根据文字描述合理设计子类的其他属性和方法。 (2)设计实现画板类,要求: ①画一个红色、无填充、长和宽分别为10.0与5.0的长方形; ②画一个绿色、有填充、半径为3.0的圆形; ③画一个黄色、无填充、边长为4.0的正方形; ④分别求三个对象的面积和周长,并将每个对象的所有属性信息打印到控制台。
//抽象类 图形类
public abstract class Graphical {
private String colour;
private boolean fill;
public abstract double perimeter();
public abstract double area();
public abstract String toString() ;
public Graphical() {
}
public Graphical(String colour, boolean fill) {
this.colour = colour;
this.fill = fill;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public boolean isFill() {
return fill;
}
public void setFill(boolean fill) {
this.fill = fill;
}
}
//正方形类
public class Square extends Graphical{
private double side;
public Square(String colour, boolean fill, double side) {
super(colour, fill);
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double perimeter() {
return 2*side;
}
public double area() {
return side*side;
}
public String toString() {
return "正方形的颜色为:"+getColour()+"\t有无填充:"+isFill()+"边长为:"+getSide()+"周长为:"+perimeter()+"面积为:"+area();
}
}
//长方形类
public class Rectangle extends Graphical{
private double length;
private double width;
public Rectangle(String colour, boolean fill, double length,double width) {
super(colour, fill);
this.length = length;
this.width= width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double perimeter() {
return (length+width)*2;
}
public double area() {
return length*width;
}
@Override
public String toString() {
return "长方形的颜色为:"+getColour()+"\t有无填充:"+isFill()+"长为:"+getLength()+"宽为:"+getWidth()+"周长为:"+perimeter()+"面积为:"+area();
}
}
//子类 圆形类
public class Circular extends Graphical {
private double R;
public Circular(String colour, boolean fill, double r) {
super(colour, fill);
R = r;
}
public double getR() {
return R;
}
public void setR(double r) {
R = r;
}
public double perimeter() {
return R*2*3.14;
}
public double area() {
return R*R*3.14;
}
public String toString() {
return "圆的颜色为:" +getColour() +"\t"+"有无填充:" +isFill()+ "半径为:"+getR()+"的圆形面积为:"+area()+"周长为:"+perimeter() ;
}
}
//测试类
public class Text {
public static void main(String[] args) {
Circular circular=new Circular("绿色",true,3.0);
System.out.println(circular.toString());
Rectangle rectangle=new Rectangle("红色",false,10.0,5.0);
System.out.println(rectangle.toString());
Square square=new Square("黄色",false,4.0);
System.out.println(square.toString());
}
}