zoukankan      html  css  js  c++  java
  • Java抽象类和抽象方法例子

    题目:定义Shape类表示一般二维图形。Shape具有抽象方法area和perimeter,分别计算形状的面积和周长。试定义一些二维形状类(如矩形、三角形、圆形等),这些均为Shape类的子类并计算出这些形状的面积和周长,打印输出相关信息。

    代码:

    //形状类
    public
    abstract class Shape { public abstract double area(); public abstract double perimeter(); }
    //矩形类
    public
    class Rectangle extends Shape { private double length; private double 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; } @Override public double area() { return getLength() * getWidth(); } @Override public double perimeter() { return 2 * (getWidth() + getWidth()); } }
     
    //三角形类
    public class Triangle extends Shape { private double a, b, c; public double getA() { return a; } public void setA(double a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public double getC() { return c; } public void setC(double c) { this.c = c; } @Override public double area() { double p = (getA() + getB() + getC()) / 2; return Math.sqrt(p * (p - getA()) * (p - getB()) * (p - getC())); } @Override public double perimeter() { return getA() + getB() + getC(); } }
    //圆形类
    public
    class Circle extends Shape { private double diameter; public double getDiameter() { return diameter; } public void setDiameter(double diameter) { this.diameter = diameter; } @Override public double area() { return Math.PI * Math.pow(getDiameter() / 2, 2); } @Override public double perimeter() { return Math.PI * getDiameter(); } }
    //测试代码
    public class 测试 { public static void main(String [] args){ Rectangle rec = new Rectangle(); rec.setLength(10); rec.setWidth(5); double rec_area = rec.area(); double rec_perimeter = rec.perimeter(); System.out.println("矩形的面积:"+rec_area+",周长"+rec_perimeter); Triangle tri = new Triangle(); tri.setA(3); tri.setB(4); tri.setC(5); double tri_area = tri.area(); double tri_perimeter = tri.perimeter(); System.out.println("三角形的面积:"+tri_area+",周长"+tri_perimeter); Circle cir = new Circle(); cir.setDiameter(10); double cir_area = cir.area(); double cir_perimeter = cir.perimeter(); System.out.println("圆形的面积:"+cir_area+",周长"+cir_perimeter); } }
  • 相关阅读:
    [导入]微软的XP和Server2003在双核CPU上有缺陷
    [导入]可怜的软件开发
    [CZoneSoft]在Firefox里播放wmv流媒体视频
    [导入]直接用IL改写别人的程序
    [导入]清除3721的中文上网插件CNS
    [导入]完成可脚本调用的视频录制控件
    垃圾短信投诉的地方和方法
    [导入]不需要服务器端的在线录制视频
    [导入]各银行跨行提款收费比较
    [导入]电热水器选购
  • 原文地址:https://www.cnblogs.com/guwei4037/p/6021053.html
Copyright © 2011-2022 走看看