为了账号安全,请及时绑定邮箱和手机立即绑定

接口作为函数的参数 - 消息

接口作为函数的参数 - 消息

慕姐8265434 2022-06-23 16:21:37
我正在尝试向公司发送消息;我使用一个包含 sendMessage() 方法的接口;但我不确定如何从不同的类访问此方法。我想我可能会使用匿名类,但我不是 100% 确定..我试图创建一个匿名类,但我必须从我无权访问的接口覆盖 sendMessage() 方法。重写不会破坏接口方法吗?public interface Company {void sendMessage(Message my_message);//i am not able to view whats inside this method }消息基本上是一个包含字符串消息和 ID 的结构。所以     Message consists of:     -name     -ID      public final class Message{      final String name = "Hello";      final long ID = "2.000";      }我想使用该界面初始化一家公司。我在另一个名为 Sender 的类中有一个 initialiseCompany 方法和一个 sendThis 方法:initialiseCompany 将接口作为参数,这是我开始感到困惑的地方。sendThis 创建消息并尝试将其发送到接口中的 sendMessage() 方法。public class Sender{     public void intitaliseCompany(Company myCompany){      //what i need to complete     }     public sendThis(Message my_Message){     // here I need to send the message in my case my_Message = 'HELLO'     String inputMessage = my_Message.name;     //now i need to send the inputMessage to the chosen company     //using the sendMessage() method from the interface.     //i am not sure how to access that sendMessage method from that     //original interface}我如何从接口初始化公司,然后从不同的方法访问 sendMessage() 接口方法。此外,这段代码显然不会运行,因为没有 main 等。我不能在这里添加,因为我无法解释这一切。
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

如果我理解正确initialiseCompany()只需要为Sender对象初始化公司。这意味着您需要添加一个private Company company;字段,然后将其设置为正确的值:

this.company = myCompany;

然后sendThis()应该简单地调用sendMessage()

this.company.sendMessage(myMessage);

注意:我假设您重命名my_MessagemyMessage以符合 Java 命名约定。


查看完整回答
反对 回复 2022-06-23
  • 1 回答
  • 0 关注
  • 178 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号