java 方法里面定义接口,调用方法未在Java中实现的接口的接口中定义

I have the following scenario in Java. Let's say I have an interface, and two classes that implement this interface. As follows:

public interface myInterface {

public String printStuff();

}

public class A implements myInterface {

@Override

public String printStuff(){

return "Stuff";

}

}

public class B implements myInterface {

@Override

public String printStuff(){

return "Stuff";

}

public String printOtherStuff(){

return "Other Stuff";

}

}

How do I call the printOtherStuff method above if I define it as follows:

public void Main(){

myInterface myinterface = new B();

String str = myinterface.printOtherStuff(); // ? This does not work

}

The above calling code does not seem work. Any ideas?

解决方案

myInterface myinterface = new B();

The reference type of myinterface is myInterface. That means you can only access the methods defined in the interface. You can cast it to type B in order to make the method call.

NOTE: From here on out I'll be using the proper naming conventions.

Example

MyInterface myInterface = new B();

String str = ((B)myInterface).printOtherStuff();

Just a note on this

If you need to do this, then you need to have a look at your class design. The idea of using an interface in this way is to abstract away from the details of the object's concrete implementation. If you're having to perform an explicit cast like this, then you might want to look into either changing your interface to accommodate the necessary methods, or change your class so that the method is moved into a global location (like a util file or something).

Extra Reading

You should read about reference types here, and you should have a look at casting here. My answer is a combination of the understanding of both of these things.

As an added note, take a look at the Java Naming Conventions. This is a vital piece of information for any Java developer to make understandable code.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值