【发布时间】:2014-02-28 22:29:59
【问题描述】:
我熟悉inheritance model中的type casting。
设SuperClass and SubClass为父子类;
SuperClass superClass = new SubClass(); -- 这里实例化的object 是subclass object;
但它的reference type 是SuperClass;只有SuperClass 中的methods 可以在subclass object 上调用;不能调用在subclass 中不是inherited/overridden 的任何methods(即subclass 中的任何唯一methods)。
如果SuperClass is an interface 和SubClass implements it,我观察到与上述相同的行为。只有在SuperClass interface 中声明的那些方法才能在SubClass 对象上调用。我的理解正确吗?但是对于一些casting,我可以调用不属于接口的methods,我在下面的示例代码中观察到了这一点;
我对它的工作原理做了一些 cmets; 但我想知道这是否有意义,或者我的解释是否错误;
class Animals {
public void bark(){
System.out.println("animal is barking");
}
}
interface catIF {
public void catting();
}
interface dogIF {
public void dogging();
}
class Dog extends Animals implements dogIF {
public void bark(){
System.out.println("dog is barking");
}
public void dogging() {
System.out.println("dogging");
}
}
class Cat extends Animals implements catIF {
public void bark(){
System.out.println("cat is barking");
}
public void catting() {
System.out.println("catting");
}
}
public class Animal {
public static void main(String[] args){
dogIF dog = new Dog();
//dog.bark(); this fails
//This method actually actually exists;
//but it is not available or hidden because dogIF reference
//limits its availability; (this is similar to inheritance)
Dog dog2 = new Dog();
dog2.bark();
////prints dog is barking
Animals an =(Animals) dog;
an.bark();
//prints dog is barking
//by casting we mean, treat the dog as an animals reference
//but the object itself is a dog.
//call the bark() method of dog
//but dog did not have this method in the beginning (see first line
// in main - when instantiated with interface type)
}
}
【问题讨论】:
-
dogIF#bark()不存在,所以你是对的。方法调用在编译时根据引用的声明类型进行解析。 -
是的,你的理解完全没问题。
-
继承如果接口在 Java 中有点不稳定——我不确定是否有人真正理解它。 (我理解它足够长的时间来实现
checkcast,但规则太神秘了,我早就忘记了。) -
但是要理解的一件事是,当您进行显式转换(例如
(Animals))时,编译器会相信您所说的对象是指定的类型。在幕后,checkcast字节码可确保您所说的是真的,但编译器不知道checkcast是成功还是失败。 -
强制转换在生效前检查对象是否实现了新类型,如果没有则抛出
ClassCastException。因此,Cat或Dog扩展/实现Animals并且可以转换为Animals,但它们彼此之间没有超/子类关系,因此您不能将一个转换为另一个。虽然您可以拥有一个扩展Cat并实现dogIF的对象,但如果您想描述一只猫与狗共享后一种行为……就像我的一样,它有时会取回一个球.
标签: java inheritance interface casting