亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

接口作為函數的參數 - 消息

接口作為函數的參數 - 消息

慕姐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 關注
  • 203 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號