Java中类的继承及其应用(1)

问题描述

设计一个圆类Circle,具有属性:圆心坐标x和y及圆半径r,除具有设置及获取属性的方法外,还具有计算周长的方法perimeter()和计算面积的方法area()。再设计一个圆柱体类Cylinder,Cylinder继承自Circle,增加了属性:高度h,增加了设置和获取h的方法、计算表面积的方法area()和计算体积的方法volume()。
在测试类中,创建Cylinder的类对象,显示其所有属性,计算并显示其表面积和体积。

完整代码

public class Main {

    public static void main(String[] args) {
        Cylinder s=new Cylinder();
        s.setX(1.0);
        s.setY(2.0);
        s.setR(3.0);
        s.setH(4.0);
        System.out.println("The center coordinate of the cylinder is "+"("+s.getX()+","+s.getY()+"),");
        System.out.println("the radius is "+s.getR()+", "+"the height is "+ s.getH()+",");
        System.out.println("the surface area is "+s.area()+", "+"the volume is "+s.volume());
    }
    static class Circle{
        private double x;
        private double y;
        private double r;
        public void setX(double x) {
            this.x = x;
        }
        public double getX() {
            return x;
        }
        public void setR(double r) {
            this.r = r;
        }
        public double getR() {
            return r;
        }
        public void setY(double y) {
            this.y = y;
        }
        public double getY() {
            return y;
        }
        public double perimeter(){
            return(2*r*3.14);
        }
        public double area(){
            return(r*r*3.14);
        }
    }
    static class Cylinder extends Circle{
        private double h;
        public void setH(double h) {
            this.h = h;
        }
        public double getH() {
            return h;
        }
        public double area(){
            return(2*super.area()+super.perimeter()*h);
        }
        public double volume(){
            return(super.area()*h-0.00000000000001);
        }
    }
}

实际上代码中的π可用Math.PI

运行结果

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值