[练习题] 多态性 equals() 包装类

2 篇文章 0 订阅

如何实现向下转型?需要注意什么问题?如何解决这些问题?


使用强转符 ()

Person p = new Man();
Man m1 = (Man)p;

但可能 ClassCastException 异常。

解决方法:在强转前用 instanceof 判断类型。

if(objName instanceof ClassType){
	//...
}

if(p instanceof Man){
	Man m = (Man)p;
}

== 和 equals() 有什么区别?


== 是运算符,operator.

  • 如果是比较 primitive data types , 比较 the data value that two variables stored. (不一定 type 要相同)。
  • 如果是比较 reference type , 比较 the address value of that two objects. 

(类比“值传递机制”)

equals()是方法,method.

因为是 method, 故只能由 object( reference type ) invoke.

  • 在原始的 Object类 中,equals() 定义等同于 == 。
  • 但像 String, Date, File, 包装类等类 override 了该方法,比较的却是 object 的“实体内容” (data value they stored)
  • 通常,我们自定义的类 customized Class 用 equals() 都是想比“实体内容”,我们就需要自己对 equals() override.

Primitive data types / Wrapper Classes  &  String  怎样转换?


Primitive data types  <--->  Wrapper Classes  自动拆箱装箱

注意,转换时可能报 NumberFormatException.

谈谈你对多态性 Polymorphism 的理解?


WHAT?  The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. 

Person p = new Man();
Object o = new Date();
Animal a = new Dog();

WHY?实现代码的通用性。

i.e.,Object类中定义的equals(). i.e.,JDBC使用java操作不同的数据库。

i.e., 抽象类和接口

延伸  "向上转型"(多态),“向下转型”。

WHY 向下转型 Narrowing Typecasting ? 因为有了对象多态性后,虽然 memory 中 has loaded attributes and methods of child class, (because the Dog class extends Animal class, and the Dog class has acquired all the properties of the Animal class.)  But in view of that the reference has declared as type of parent class object reference, So when compiling, 只能 invoke parent class, 不能 invoke child class 特有的。

Narrowing typecasting occurs when a superclass object reference is narrow casted and assigned to a narrower sub-class object. Like, in the above example, an animal object was assigned to a Dog object reference.

Object类的 toString() 方法


When we output a object's reference, actually 就是 call 当前 object 的 method toString() .

JUnit单元测试


前提:该Class是 public 的 ; 该 Class 提供公共的无参的构造器 no-argument, default constructor

此 class 中声明的单元测试 method,要求权限是 public, no return value, no parameter.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值