当对象是Java中的接口引用时类型转换 [英] type casting when objects are of interface references in Java

查看:140
本文介绍了当对象是Java中的接口引用时类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉继承模型中的类型转换



SuperClass和SubClass 成为父类和子类;



SuperClass superClass = new SubClass(); - 这里实例化的对象是一个子类对象;
但其引用类型 SuperClass ;只有那些方法 SuperClass 才能在子类对象上调用;在子类中不能继承/覆盖的任何方法都不能被调用(即任何唯一的方法 子类)。



如果 SuperClass是一个接口并且 SubClass实现它,我观察到与上面相同的行为。这只是在 SuperClass接口中声明的那些方法可以在 SubClass 对象上调用。我的理解是否正确?但是有一些 cast ,我可以调用方法,这不是界面的一部分,我在我的样本中观察到了下面的代码;



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

  class Animals {

public void bark(){
System.out.println(animal is barking);
}

}

interface catIF {
public void catting();

}

interface dogIF {
public void dogging();
}

class Dog extends动物实现dogIF {

public void bark(){
System.out.println(dog is barking) ;
}


public void dogging(){
System.out.println(dogging);

}

}

class Cat extends动物实现catIF {

public void bark(){
System.out.println(猫吠);
}


public void catting(){
System.out.println(catting);

}

}

公共类Animal {

public static void main(String [] args){
dogIF dog = new Dog();
//dog.bark();这失败
//这个方法实际上存在;
//但它不可用或隐藏,因为dogIF引用
//限制了它的可用性; (这类似于继承)

Dog dog2 = new Dog();
dog2.bark();
////打印狗吠叫

动物an =(动物)狗;
an.bark();
//打印狗咆哮
//通过施放我们的意思,将狗视为动物参考
//但对象本身就是一只狗。
//调用dog
//的bark()方法但是狗在开头没有这个方法(参见第一行
//在main中 - 当用接口类型实例化时)
}
}


解决方案

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

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



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



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



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



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


I am familiar with type casting in inheritance model.

Let SuperClass and SubClass be parent and child classes;

SuperClass superClass = new SubClass(); -- Here the object instantiated is a subclass object; but its reference type is SuperClass; that is only those methods of SuperClass can be called on the subclass object; Any methods that are not inherited/overridden in subclass cannot be called (that is any unique methods of subclass).

I observed same behavior as above if SuperClass is an interface and SubClass implements it. That is only those methods declared in SuperClass interface are available to be called on the SubClass object. Is my understanding correct? But with some casting, I can call methods that is not part of the interface, which I have observed in my sample code below;

I have made some comments on my understanding as how it works; but I would like to know if that make sense or if my interpretation is wrong;

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 of interfaces really isn't "flaky" or complicated. They behave exactly the way abstract classes do, with the exceptions that you reference them differently (implements rather than extends) and that you're allowed to inherit as many interfaces as you like but can only have one superclass (abstract or not).

As with other inheritance: If all you know about an object is that it implements an interface, then you can only access it through that interface. If you know that it implements another interface, or a specific superclass, or is an instance of a particular class, then you can cast it to those and access it through the exposed members of those.

So, yes: If all your program knows is that the object is an instance of Animals, then all you can do is call what's declared on Animals. That means bark() plus whatever methods it inherits from Object (since everything is an Object directly or indirectly even if that isn't explicitly stated).

If your program knows that the object is an implementation of dogIF or catIF -- because the variable type says it is, or because you've successfully typecast it to one of those interfaces -- you can also call the method(s) declared by those interfaces. By the way, the usual convention for interfaces is to name them like classes, with UppercasedFirstLetter... since in many cases the difference between an interface and a class really isn't significant to the folks using it.

If your program happens to know that the object is a Dog, you can call anything it inherits from either Animals or dogIF, or that is provided directly by Dog. Of course it could actually be a Chihuahua (subclass of dog), but that's OK, the subclass will respond to anything the superclass would have responded to, in "the right way to maintain the semantics". (That is, a Chihuahua may respond to bark() by saying "yip yip yip grr yip!", but that method really shouldn't cause it to try to bite your ankle.)

Hope that helps. It really isn't that complicated.

这篇关于当对象是Java中的接口引用时类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆