7-12 继承类应用 (20 分)


				   继承类应用 (20 分)

创建一个名称为Square的类: 该类中定义私有的成员字段edge,定义该字段的set,get方法; 完成该类的构造方法; 该类包含方法Circumference(周长)和面积(Area); 定义子类正方体Cube类: 完成该类的构造方法; 实现该类的面积(Area)和体积(Volumn)方法。 在main中创建正方形对象,计算并显示其周长和面积;创建正方体对象,计算并显示其面积和体积。主程序调用main函数。

输入样例:
6
7
结尾无空行
输出样例:
边长为6的正方形,面积= 36
边长为6的正方形,周长= 24
边长为7的立方体,面积= 294
边长为7的立方体,体积= 343

代码:

import java.util.Scanner;

class Square{
    private int edge;

    public Square(int edge) {
        this.edge = edge;
    }

    public int getEdge() {
        return edge;
    }

    public void setEdge(int edge) {
        this.edge = edge;
    }
    public int Circumference(){
        return this.edge*4;
    }
    public int Area(){
        return this.edge*this.edge;
    }

    @Override
    public String toString() {
        return "边长为"+this.edge+"的正方形,面积= "+this.Area()+'\n'+
        "边长为"+this.edge+"的正方形,周长= "+this.Circumference();
    }
}
class Cube extends Square{
        private int edge;
    public Cube(int edge) {
        super(edge);
        this.edge=edge;
    }

    public int Circumference(){
        return this.edge*this.edge*6;
    }
    public int Area(){
        return (int)Math.pow(this.edge,3);
    }

    @Override
    public String toString() {
        return "边长为"+edge+"的立方体,面积= "+this.Circumference()+'\n'+
                "边长为"+this.edge+"的立方体,体积= "+this.Area();
    }
}
public class Main{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        Square s1=new Square(sc.nextInt());
        Cube s2=new Cube(sc.nextInt());
        System.out.println(s1.toString());
        System.out.println(s2.toString());
    }
}


版权声明:本文为qq_51187952原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。