zoukankan      html  css  js  c++  java
  • 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());
    	}
    
    }
    

    运行结果:

  • 相关阅读:
    Spring源码学习之容器的基本实现(一)
    面向对象设计原则
    简单易懂带你了解红黑树
    简单易懂带你了解二叉树
    单例模式
    原形模式
    数组与链表
    记一次解决postgresql数据库内存泄露的问题
    记一次排查CPU高的问题
    react ts 设置paths 和 声明非@types的模块
  • 原文地址:https://www.cnblogs.com/klvchen/p/14452289.html
Copyright © 2011-2022 走看看