instanceof操作符

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
c instanceof B:左边是对象,右边是类,如果创建c的类是B或者B的子类,那么返回True,可以向下转型
比如:C是B的子类,B是A的子类,①A c = new C(); 那么②B c = (B)c;就是将A类型的c向下转型为B了,因为创建对象的时候加载的是C类,而AB都是C的父类,所以AB中使用的方法,在加载中都有,都可以使用,所以可以转型
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
#是protected的意思

package com.instanceOf.java;

public class GeometricObject {

	protected String color;
	protected double weight;
	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;
	}
	
	public double findArea() {
		return 0;
	}
}

package com.instanceOf.java;

public class Circle extends GeometricObject{

	private double radius;

	public Circle(String color, double weight, double radius) {
		super(color, weight);
		this.radius = radius;
	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}
	
	public double findArea() {
		return radius*radius*Math.PI;
	}
}

package com.instanceOf.java;

public class MyRectangle extends GeometricObject{

	private double width;
	private double height;
	public MyRectangle(String color, double weight, double width, double height) {
		super(color, weight);
		this.width = width;
		this.height = height;
	}
	public double getWidth() {
		return width;
	}
	public void setWidth(double width) {
		this.width = width;
	}
	public double getHeight() {
		return height;
	}
	public void setHeight(double height) {
		this.height = height;
	}
	
	public double findArea() {
		return width*height;
	}
}

package com.instanceOf.java;

public class GeomatricTest {

	public static void main(String[] args) {
		
		GeomatricTest test = new GeomatricTest();
		Circle c1 = new Circle("red",100,1);
		MyRectangle rec = new MyRectangle("red",100,1,4);
		boolean isEquals = test.equalsArea(c1,rec);
		if(isEquals) {
			System.out.println("面积相等");
		}else {
			System.out.println("面积不等");
		}
		test.displayGeometricObject(c1);
		test.displayGeometricObject(rec);
	}
	
	public boolean equalsArea(GeometricObject c,GeometricObject rec) {
		return (c.findArea() == rec.findArea());
	}
	public void displayGeometricObject(GeometricObject geo) {
		System.out.println(geo.findArea());
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

新手学java2021

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

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

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

打赏作者

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

抵扣说明:

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

余额充值