java 接口转化为对象,在java中将对象转换为接口?

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();

Thanks for your help

解决方案

MyInterface myObj = new Obj();

MyInterface mySec = new Sec();

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();

}

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.

but i also read that if we declare the object myObj as MyInterface,

myObj won't be able to use its own methods (from the class Obj), is

that correct

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

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值