5-7面向对象编程(中)----Object类的使用练习

1.定义两个类,父类GeometricObject代表几何形状,子类Circle代表圆形。
在这里插入图片描述
在这里插入图片描述

写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否相等;利用toString()方法输出其半径。
Circle类:

package exer4;
 
public class Circle extends GeometrivObject {
 private double radius;
 
 public Circle() {
  super();
  radius = 1.0;
 }
 
 public Circle(double radius) {
  super();
  this.radius = radius;
 }
 
 public Circle(double radius, String color, double weight) {
  super(color, weight);
  this.radius = radius;
 }
 
 public double getRadius() {
  return radius;
 }
 
 public void setRadius(double radius) {
  this.radius = radius;
 }
 
 public double findArea() {
  return Math.PI * radius * radius;
 }
 
 // 比较两个圆的半径是否相等,如果相等,返回true
 @Override
 public boolean equals(Object obj) {
  if (this == obj) {
   return true;
  }
  if (obj instanceof Circle) {
   Circle c = (Circle) obj;
   return this.radius == c.radius;
  }
  return false;
 }
 
 @Override
 public String toString() {
  return "Circle [radius=" + radius + "]";
 }
}

GeometrivObject类:

package exer4;
 
public class GeometrivObject {
 protected String color;
 protected double weight;
 
 public GeometrivObject() {
  super();
  this.color = "white";
  this.weight = 1.0;
 }
 
 public GeometrivObject(String color, double weight) {
  super();
  this.color = color;
  this.weight = weight;
 }
 
 public String getColor() {
  return color;
 }
 
 public void setColor(String color) {
  this.color = color;
 }
 
 public double getWeight() {
  return weight;
 }
 
 public void setWeight(double weight) {
  this.weight = weight;
 }
 
}

CircleTest类:

package exer4;
 
public class CircleTest {
 public static void main(String[] args) {
  Circle circle1 = new Circle(2.3);
  Circle circle2 = new Circle(3.3, "white", 2.0);
  System.out.println("颜色是否相等:" + circle1.getColor().equals(circle2.getColor()));
  System.out.println("半径是否相等:" + circle1.equals(circle2));
  System.out.println(circle1);
  System.out.println(circle2.toString());
 }
}

输出:

颜色是否相等:true
半径是否相等:false
Circle [radius=2.3]
Circle [radius=3.3]
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YY鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值