如何实现向下转型?需要注意什么问题?如何解决这些问题?
使用强转符 ()
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.