java中instanceof和的区别,java中instanceof和getClass()的区别分析

class a { }

class b extends a { }

object o1 = new a();

object o2 = new b();

o1 instanceof a => true

o1 instanceof b => false

o2 instanceof a => true // <================ here

o2 instanceof b => true

o1.getclass().equals(a.class) => true

o1.getclass().equals(b.class) => false

o2.getclass().equals(a.class) => false // <===============here

o2.getclass().equals(b.class) => true

getclass() will be useful when you want to make sure your instance is not a subclass of the class you are comparing with.

一个非常完美的equals方法的写法:

public boolean equals(object otherobject)

{

// a quick test to see if the objects are identical

if (this == otherobject) return true;

// must return false if the explicit parameter is null

if (otherobject == null) return false;

// if the classes don't match, they can't be equal

if (getclass() != otherobject.getclass()) return false;

// now we know otherobject is a non-null employee

employee other = (employee) otherobject;

// test whether the fields have identical values

return name.equals(other.name) && salary == other.salary && hireday.equals(other.hireday);

}

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值