image.pngimage.png

    1. package com.atguigu.exercise5;
    2. public class GeometricObject {//几何形状
    3. //属性
    4. protected String color;
    5. protected double weight;
    6. //构造器
    7. protected GeometricObject(){
    8. this.color = "white";
    9. this.weight = 1.0;
    10. }
    11. protected GeometricObject(String color,double weight){
    12. this.color = color;
    13. this.weight = weight;
    14. }
    15. //方法
    16. public String getColor(){
    17. return color;
    18. }
    19. public void setColor(String color){
    20. this.color = color;
    21. }
    22. public double getWeight() {
    23. return weight;
    24. }
    25. public void setWeight(double weight) {
    26. this.weight = weight;
    27. }
    28. }

    1. package com.atguigu.exercise5;
    2. public class Circle extends GeometricObject {// 圆形
    3. // 属性
    4. private double radius;
    5. // 构造器
    6. public Circle() {
    7. super();
    8. radius = 1.0;
    9. // color = "white";
    10. // weight = 1.0; // super()中已经包含了这两个属性
    11. }
    12. public Circle(double radius) {
    13. super();
    14. this.radius = radius;
    15. }
    16. public Circle(double radius, String color, double weight) {
    17. super(color, weight);
    18. this.radius = radius;
    19. }
    20. // 方法
    21. public double getRadius() {
    22. return radius;
    23. }
    24. public void setRadius(double radius) {
    25. this.radius = radius;
    26. }
    27. // 计算圆的面积
    28. public double findArea() {
    29. return Math.PI * radius * radius;
    30. }
    31. //比较两个圆的半径是否相等,如果相等,返回true
    32. @Override
    33. public boolean equals(Object obj) {
    34. if(this == obj){
    35. return true;
    36. }
    37. if(obj instanceof Circle){
    38. Circle c = (Circle)obj;
    39. return this.radius == c.radius;
    40. }
    41. return false;
    42. }
    43. //输出圆的半径
    44. @Override
    45. public String toString() {
    46. return "Circle [radius =" + radius + "]";
    47. }
    48. }

    1. package com.atguigu.exercise5;
    2. public class CircleTest {
    3. public static void main(String[] args) {
    4. Circle circle1 = new Circle(2.3);
    5. Circle circle2 = new Circle(2.3, "white", 2.0);
    6. //判断颜色是否相同
    7. System.out.println("颜色是否相同:"+ circle1.getColor().equals(circle2.getColor()));
    8. //判断半径是否相同
    9. System.out.println("半径是否相同:"+ circle1.equals(circle2));
    10. System.out.println(circle1);
    11. System.out.println(circle2.toString());
    12. }
    13. }