• java类的练习 -- 声明一个接口(Calculability),接口中


    java类的练习 – 声明一个接口(Calculability),接口中…

    题目

    编写一个应用程序,实现以下功能:

    ①声明一个接口(Calculability),接口中包含一个方法area()

    ②声明一个三角形类实现该接口,类名为Triangle,类中包含两个变量、一个带参数的构造方法和一个计算三角形面积的方法:

    三角形的底边长w

    三角形的高h

    构造方法Triangle(double width,double height)

    计算三角形面积的方法area(),该方法覆盖接口(Calculability)的同名方法,计算三角形的面积(w*h/2)

    ③声明一个锥体类(Taper),包含一个接口对象bottom(锥体的底)和一个变量(锥体的高)height,一个带参数的构造方法,一个换底方法setBottom(),一个锥体体积的计算方法volume()

    参考代码

    // 参考文件名 Ch4.java
    
    //声明一个接口
    interface Calculability {
    	public double area();
    }
    
    // 三角形类
    class Triangle implements Calculability { 
    	private double w;
    	private double h;
    
    	public Triangle(double width, double hight) {
    		this.h = hight;
    		this.w = width;
    	}
    
    	public double area() {
    		return h * w * 0.5;
    	}
    }
    
    // 锥体类
    class Taper implements Calculability { 
    	private double h;
    	Triangle b;
    
    	public Taper(double height, Triangle bottom) { 
    		this.h = height;
    		this.b = bottom;
    	}
    
    	public void setbottom(Triangle bott) {
    		this.b = bott;
    	}
    	
    	public double area() {
    		return b.area();
    	}
    	public double volume() {
    		return b.area() * h * 1.0 / 3;
    	}
    }
    
    public class Ch4 {
    	public static void main(String args[]) {
    		Triangle bottom1 = new Triangle(2, 2);
    		Taper zhui = new Taper(6, bottom1);
    		System.out.println("椎体的底面积为:" + (bottom1.area() + ""));
    		System.out.println("椎体的体积为:" + (zhui.volume() + ""));
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    在这里插入图片描述
    仅供参考,欢迎指正、交流、学习,摇一摇

  • 相关阅读:
    PaddleNLP UIE -- 药品说明书信息抽取(名称、规格、用法、用量)
    面试突击:说一下 Spring 中 Bean 的生命周期?
    数位dp,338. 计数问题
    webpack打包TypeScript代码
    nodejs,vue,element 这三者是什么关系?
    Apache Doris的数据导入insert、数据删除delete
    测试/开发程序员的成长路线,全局思考问题的问题......
    mysql 截取字段串字段转换成时间格式
    灵境:为每个一需要的人配上一个后台
    6、规划绩效域
  • 原文地址:https://blog.csdn.net/m0_51126511/article/details/127890914