当对象是Java中的接口引用时类型转换

我熟悉inheritance model type casting

SuperClass and SubClass成为父类和子类;

SuperClass superClass = new SubClass() ; – 这里实例化的objectsubclass object ; 但它的reference typeSuperClass ; 那只是可以在subclass object上调用SuperClass那些methods ; 不能调用任何未在subclass inherited/overridden methods (即subclass任何唯一methods )。

如果SuperClass is an interfaceSubClass implements it我观察到与上面相同的行为。 这只是在SuperClass interface中声明的那些方法可以在SubClass对象上调用。 我的理解是否正确? 但是通过一些casting ,我可以调用不属于接口的方法,我在下面的示例代码中观察到了这些方法;

我对我的理解做了一些评论,说明它是如何运作的; 但我想知道这是否有意义,或者我的解释是否错误;

 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) } } 

接口的inheritance确实不是“片状”或复杂的。 它们的行为与抽象类的行为完全相同,例外情况是您以不同方式引用它们(实现而不是扩展),并且允许您inheritance任意数量的接口,但只能有一个超类(抽象或不抽象)。

与其他inheritance一样:如果您对对象的了解是它实现了一个接口,那么您只能通过该接口访问它。 如果您知道它实现了另一个接口,或特定的超类,或者是特定类的实例,那么您可以将其强制转换为那些接口,并通过这些接口的公开成员进行访问。

所以,是的:如果您的所有程序都知道对象是Animals的实例,那么您所能做的就是调用动物上声明的内容。 这意味着bark()加上它从Objectinheritance的任何方法(因为即使没有明确说明,所有东西都是直接或间接的Object )。

如果您的程序知道该对象是dogIFcatIF的实现 – 因为变量类型表明它是,或者因为您已成功将其类型转换为其中一个接口 – 您还可以调用由那些接口。 顺便说一句,接口的通常惯例是使用UppercasedFirstLetter将它们命名为类,因为在很多情况下,接口和类之间的差异对于使用它的人来说并不重要。

如果您的程序碰巧知道该对象是Dog ,您可以调用它inheritance自AnimalsdogIF任何dogIF ,或者由Dog直接提供的内容。 当然它实际上可能是Chihuahua (狗的子类),但是没关系,子类将以“以正确的方式维护语义”来响应超类将响应的任何内容。 (也就是说, Chihuahua可以通过说“yip yip yip yr grr yip!”来回应bark() ,但这种方法真的不应该让它试图咬你的脚踝。)

希望有所帮助。 这真的不是那么复杂。