作业2020.12.15
第十章作业代码
第一题,求面积:
1,父类
package homework01;
//定义抽象类Area
abstract class Area {
public abstract double area();//定义抽象方法
}
2,子类1
package homework01;
class RoundArea extends Area{
private double radius; //定义半径
public RoundArea() {
}
public RoundArea(double radius) {
this.radius = radius;
}
public double area() {
return Math.PI * this.radius *this.radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
}
3,子类
package homework01;
//定义矩形子类
public class RectArea extends Area{
private double length;//定义长度
private double width;//定义宽度
public RectArea(){
}
public RectArea(double length,double width) {
this.length = length;
this.width = width;
}
public double area(){
return this.length*this.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;
}
}
4,测试类
package homework01;
import java.util.Scanner;
public class Test {
public void test(){
Scanner sc = new Scanner(System.in);
Area a;
a = new RoundArea();
System.out.println("请输入圆的半径:");
((RoundArea)a).setRadius(sc.nextDouble());
System.out.println("圆的面积为:" + a.area());
Area b;
b = new RectArea();
System.out.println("请输入长:");
((RectArea)b).setLength(sc.nextDouble());
System.out.println("请输入宽:");
((RectArea)b).setWidth(sc.nextDouble());
System.out.println("长方形的面积为:"+b.area());
}
public static void main(String[] args) {
Test sum = new Test();
sum.test();
}
}
近期评论