本文介绍了在java中将对象转换为接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将对象强制转换为接口,该对象将无法调用其自己的方法吗?在下面的示例中,myObj将只能调用MyInterface方法吗?

if we cast an object to an interface, won't this object be able to call its own methods? in the following example, myObj will only be able to call MyInterface methods?

MyInterface myObj = new Obj();

如果这是正确的,那两个对象之间的区别是什么?

If this is correct, what is the difference between those 2 objects :

MyInterface myObj = new Obj();

MyInterface mySec = new Sec();

感谢您的帮助

推荐答案

MyInterface myObj = new Obj();
MyInterface mySec = new Sec();

为使其合法,ObjSec都必须是MyInterface的实现者.这两个对象之间的区别是它们提供该实现的方式. ObjSec可以做两个非常不同或非常相似的事情,但是它们的共同点是它们将遵守您可以依赖的合同.考虑您有方法

For this to be legal, both Obj and Sec will have to be implementers of MyInterface. The difference between these two objects would be how they provide that implementation. Obj and Sec could do two very different or very similar things, but their commonality is that they would adhere to a contract that you could rely upon. Consider you have a method

public void doSomethingWith(MyInterface thing) {
     thing.frob();
}

每个对象myObjmySec可以传递到此方法中,然后该方法可以使用该对象的frob方法(假设frob是接口声明的一部分).这是解放.通过对接口而不是对实现进行编程,这使您可以做非常强大的事情.例如,您可以扩展类的功能,而无需更改这些类中的代码行,您只需传递依赖项的不同实现即可.您与方法doSomethingWith内的任何一种实现都没有任何束缚或联系.

Each object, myObj and mySec, could be passed into this method, and this method could then use that object's frob method (assuming frob is part of the interface declaration). This is liberating. This allows you to do very powerful things, by programming to interfaces and not to implementations. For example, you can extend functionality of classes and not change a line of code in those classes, you simply pass a different implementation of a dependency. You are not tied to, or coupled with, any one implentation inside the method doSomethingWith.

在内部,Obj的实例将继续具有对Obj API的完全访问权限. myObj仍然是Obj,它将始终能够使用其自己的实现详细信息.

Internally, instances of Obj will continue to have full access to the Obj API. myObj is still an Obj, it will always be able to use its own implementation details.

public interface MyInterface {
    void frob();
}

public class Obj implements MyInterface {

    public void frob() {
        doFrobbing();
    }

    private void doFrobbing() {
        System.out.println("frobbing");
    }

    public static void main(String[] args) {
        MyInterface myObj = new Obj();
        myObj.frob(); // still internally calls doFrobbing()
        ((Obj)myObj).doFrobbing(); // visible only via class reference
    }
}

Obj的实例仍将是Obj的实例,并且这些实例仍将能够使用doFrobbing.在外部,通过接口引用使用这些实例的人只能访问接口方法.

Instances of Obj will still be instances of Obj, and those instances will still be able to use doFrobbing. Externally, persons using those instances via the interface reference will only be able to access the interface methods.

这篇关于在java中将对象转换为接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:51