当前位置:   article > 正文

Java面向对象练习(2) (2024.7.11)

Java面向对象练习(2) (2024.7.11)

        圆类

  1. package area20240711;
  2. public class Circle extends Picture{
  3. private double r;
  4. private final double PI = 3.1415926;
  5. public Circle(){}
  6. public Circle(double r) {
  7. this.r = r;
  8. }
  9. public double getR() {
  10. return r;
  11. }
  12. public void setR(double r) {
  13. this.r = r;
  14. }
  15. public double getPI() {
  16. return PI;
  17. }
  18. @Override
  19. public double length() {
  20. return 2 * PI * this.r;
  21. }
  22. @Override
  23. public double area() {
  24. return this.r * this.r * PI;
  25. }
  26. }

        图形类

  1. package area20240711;
  2. public abstract class Picture {
  3. public abstract double length();
  4. public abstract double area();
  5. }

        矩形类

  1. package area20240711;
  2. public class Rectangle extends Picture{
  3. private double length;
  4. private double width;
  5. public Rectangle(){}
  6. public Rectangle(double length, double width) {
  7. this.length = length;
  8. this.width = width;
  9. }
  10. public double getLength() {
  11. return length;
  12. }
  13. public void setLength(double length) {
  14. this.length = length;
  15. }
  16. public double getWidth() {
  17. return width;
  18. }
  19. public void setWidth(double width) {
  20. this.width = width;
  21. }
  22. @Override
  23. public double length() {
  24. return 2.0 * (this.length + this.width);
  25. }
  26. @Override
  27. public double area() {
  28. return this.length * this.width * 1.0;
  29. }
  30. }

        测试

  1. package area20240711;
  2. import java.util.Scanner;
  3. public class AreaTest {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. // 创建一个矩形
  7. Rectangle rtg = creatRectangle();
  8. System.out.println("长为" + rtg.getLength() + "宽为" + rtg.getWidth()
  9. + "的矩形的周长是" + rtg.length());
  10. System.out.println("长为" + rtg.getLength() + "宽为" + rtg.getWidth()
  11. + "的矩形的面积是" + rtg.area());
  12. // 创建一个圆形
  13. Circle c = creatCircle();
  14. System.out.println("半径为" + c.getR() + "圆的周长是" + c.length());
  15. System.out.println("半径为" + c.getR() + "圆的面积是" + c.area());
  16. }
  17. public static Rectangle creatRectangle () {
  18. Scanner sc = new Scanner(System.in);
  19. System.out.println("请输入矩形的长");
  20. double length = sc.nextDouble();
  21. System.out.println("请输入矩形的宽");
  22. double width = sc.nextDouble();
  23. return new Rectangle(length, width);
  24. }
  25. public static Circle creatCircle() {
  26. Scanner sc = new Scanner(System.in);
  27. System.out.println("请输入圆形的半径");
  28. double r = sc.nextDouble();
  29. return new Circle(r);
  30. }
  31. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/828129
推荐阅读
相关标签
  

闽ICP备14008679号