![](/img/trans.png)
[英]How does the parent class's defined method get called in a sub-class object?
[英]How to call an Object's Method from another class without creating a sub-class and/or inheriting class?
我一直在初學階段學習基本代碼。 現在我終於開始涉足實際編寫簡單的程序,並且真的陷入困境。
我正在寫一個簡單的程序,它由兩個類組成; 人,MainPage。
程序運行后,方法openApp()
在main方法中從(MainPage Class)調用。
public static void main(String[] args) { openApp(); }
接下來,當調用openApp()
,用戶有三個菜單可供選擇,通過輸入相應的數字來選擇
即1 =新聞源,2 =個人資料或3 =朋友。
公共類MainPage {
public static void openApp() {
System.out.println("Welcome to App!");
System.out.println();
System.out.println("To Select Option for:");
System.out.println("Newsfeed : 1");
System.out.println("Profile : 2");
System.out.println("Friends : 3");
System.out.println("Enter corresponding number: ");
int optionSelected = input.nextInt();
switch (optionSelected) {
case 1: System.out.println("NewsFeed");
break;
case 2: System.out.println("Profile");
break;
case 3: System.out.println("Friends");
break;
if (optionSelected == 3) {
people.friend();// Is it possible to write: friend() from "People" Class without extending to People Class
}
}
}
friend(People name)
,用於打印人對象的朋友。 我的嘗試:
if (optionSelected == 3) {
people.friend();
}
我得到的錯誤:
線程“main”中的異常java.lang.Error:未解決的編譯問題:無法解析人員
問題是我不想在MainPage中擴展People Class並繼承它的所有方法,但我仍然想從People Class調用Object方法來打印people對象的朋友。
注意:以防任何人想要查看位於People類中的friend(People people)
方法:
public void friend(People people) {
System.out.println(people.friend);
優秀的問題格式。
您可以聲明類型為People
的Object
,並使用它。
例
public class MainPage
{
People people = new People();
// .. Some code.
if(optionSelected == 3) {
people.friend();
}
}
說明
您的friend
方法是一種instance method
。 這意味着要訪問它,您需要創建一個對象實例。 這是通過new
關鍵字完成的。 其次,除非People
是某種形式的實用類,否則你的friend
方法應該更像是:
public void friend()
{
System.out.println(this.friend);
}
為了良好的代碼設計,請記住您的MainPage
類正在輸出給用戶,因此您應該return
值而不是打印它。 其次,您應該遵循良好的命名標准,在Java
我們在獲取類成員時使用get
前綴。
public void getFriend()
{
return this.friend;
}
在MainPage
類中,您應該打印它。
if(optionSelected == 3)
{
System.out.println(people.getFriend());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.