多态——动态绑定(实验)

定义三个类,父类GeometricObject代表几何形状,子类Circle代表圆形,MyRectangle代表矩形。
在这里插入图片描述
定义一个测试类Test,编写equalsArea方法测试两个对象的面积是否相等(注意方法的参数类型,利用动态绑定技术),编写displayGeometricObject方法显示对象的面积(注意方法的参数类型,利用动态绑定技术)

这里先给出GeometricObject类

package Polymorphic;
//GeometricOblect
/**
 * @author 刘
 *
 */
public class Geometric {
	protected String Color; //颜色
	protected double Weight;
	protected Geometric(String a,double b){
		Color=a;Weight=b;
	}
	public String getColor() {
		return Color;
	}
	public void setColor(String color) {
		Color = color;
	}
	public double getWeight() {
		return Weight;
	}
	public void setWeight(double weight) {
		Weight = weight;
	}
	public double findArea() {
		return 0;
	}
	public boolean equalsArea(Geometric another){ //动态绑定
		return findArea() == another.findArea();  
	}
	public void displayArea() {//动态绑定
		System.out.println(findArea());
	}
}

然后是Circle类

package Polymorphic;

public class Circle extends Geometric{
	private double radius; //半径
	Circle(double a,String b,double c){
		super(b,c);
		radius=a;
	}
	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}
	public double findArea() {//圆面积计算
		return 3.14*radius*radius;
	}
}

然后是Rectangle类

package Polymorphic;

public class Rectangle extends Geometric {
	private double hight;  //长
	private double width;  //宽
	Rectangle(double a,double b,String c,double d){
		super(c,d);
		hight=a;
		width=b;
	}
	public double getHight() {
		return hight;
	}
	public void setHight(double hight) {
		this.hight = hight;
	}
	public double getWidth() {
		return width;
	}
	public void setWidth(double width) {
		this.width = width;
	}
	public double findArea() {//面积计算
		return width*hight;
	}
}

最后是测试类Test

package Polymorphic;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Rectangle myrec=new Rectangle(1.14,1,"red",3);//一个长为1.14,宽为1的长方形,红色,3磅
		Circle mycir=new Circle(2,"Green",4);//一个半径为2的圆形,绿色,4磅
		System.out.println(myrec.equalsArea(mycir));//比较这个圆和长方形的面积,相等返回布尔值true,不相等返回布尔值false
		myrec.displayArea();//显示长方形面积的数值
		mycir.displayArea();//显示圆的面积数值
	}
}

在Test中,长方形的面积为1.14,圆的面积为12.56,面积不等,equalsArea()函数返回false,故而有下面的输出结果:
在这里插入图片描述

修改Test类中的代码,让面积相等,观察函数equalsArea()的返回:

package Polymorphic;

public class Test{

	public static void main(String[] args){
	// TODO Auto-generated method stub
	Rectangle myrec=new Rectangle(12.56,1,"red",3);//一个长为12.56,宽为1的长方形,红色,3磅
  	Circle mycir=new Circle(2,"Green",4);//一个半径为2的圆形,绿色,4磅
  	System.out.println(myrec.equalsArea(mycir));//比较这个圆和长方形的面积,相等返回布尔值true,不相等返回布尔值false
  	myrec.displayArea();//显示长方形面积的数值
 	 mycir.displayArea();//显示圆的面积数值
 }

在这里插入图片描述
这里,我们就验证了动态绑定的可行性,它能更方便的为程序员的编程,减少代码量;

猜你喜欢

转载自blog.csdn.net/qq_39237781/article/details/82917474