老师帮忙检查下
来源:4-4 编程练习
慕沐2169693
2019-09-25 16:48:27
abstract class Shape {
public abstract double area();
}
public class Circle extends Shape {
private double r;
//创建带参构造方法以及无参构造方法
public Circle(double r){
this.setR(r);
}
public Circle(){
}
//创建针对半径的赋值和取值方法
public void setR(double r){
this.r=r;
}
public double getR(){
return this.r;
}
//重写父类中area()方法
public double area(){
double area=3.14*this.getR()*this.getR();
return area;
}
}
public class Rectangle extends Shape {
private double length,wide;
//创建带参构造方法以及无参构造方法
public Rectangle(double length,double wide){
this.setLength(length);
this.setWide(wide);
}
public Rectangle(){
}
//创建针对长、宽的赋值和取值方法
public void setLength(double length){
this.length=length;
}
public double getLength(){
return this.length;
}
public void setWide(double wide){
this.wide=wide;
}
public double getWide(){
return this.wide;
}
//重写父类的area()方法
public double area(){
double area=this.getLength()*this.getWide();
return area;
}
}
public class Test {
public static void main(String[] args) {
//创建类的实例,并分别对圆的半径和矩形的长宽进行赋值
Rectangle one=new Rectangle(6,5);
Circle two=new Circle(3);
//调用area()方法,输出结果
System.out.println("圆的面积是:"+two.area());
System.out.println("矩形的面积是"+one.area());
}
}
1回答
好帮手慕酷酷
2019-09-25
同学你好,程序完成得很好,但是还可以进行代码优化,建议Test类中使用多态的方式进行创建实例哦~可以提高了代码的扩展性。
具体如下:

修改后的代码如下:
public class Test {
public static void main(String[] args) {
// 创建类的实例,并分别对圆的半径和矩形的长宽进行赋值
Shape one = new Rectangle(6, 5);
Shape two = new Circle(3);
// 调用area()方法,输出结果
System.out.println("圆的面积是:" + two.area());
System.out.println("矩形的面积是" + one.area());
}
}如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题