Java 练习(Object 练习二)

例子一


GeometricObject.java

package com.klvchen.exer3;

public class GeometricObject {
	
	protected String color;
	protected double weight;
	
	public GeometricObject() {
		super();
		this.color = "white";
		this.weight = 1.0;
	}

	public GeometricObject(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;
	}
}

Circle.java

package com.klvchen.exer3;

public class Circle extends GeometricObject {
	                 
	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 3.14 * 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 + "]";
	}
	
}

CircleTest.java

package com.klvchen.exer3;

public class CircleTest {
	public static void main(String[] args) {
		
		Circle circle1 = new Circle(2.3);
		Circle circle2 = new Circle(2.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());
	}

}

运行结果:

posted @ 2021-02-26 15:29  klvchen  阅读(80)  评论(0编辑  收藏  举报