簡體   English   中英

引用另一類中的方法

[英]Referring to a method in another class

我有一個名為Hive的類,其中包含一些實例變量,例如Honey。 我有另一個名為Queen的類,我想使用一個名為takeHoney()的方法,在我的蜂巢類中,該方法可以除去2個蜂蜜(如果有)。 我試圖做的是在Queen類中添加一個構造函數,該構造函數將Hive作為參數並將其存儲在本地,這樣我就可以從Queen訪問Hive中的方法,但是它不起作用。 問題是什么?

public class Queen extends Bee{

    int type = 1;

    public Queen(Hive hive){

    }

    public Queen(int type, int age, int health){
        super(type, age, health);
    }

    public Bee anotherDay(){
        return this;
    }

    public boolean eat(){
        if(Hive.honey > 2){
            hive.takeHoney(2);
            return true;
        }else{
            return false;
        }   
    }
} 

您必須創建一個Hive實例才能從Hive調用方法

public class Queen extends Bee{

    int type = 1;
-->    Hive hive = null;
    public Queen(Hive h){
   -->         hive = h;
        }

    public Queen(int type, int age, int health){
        super(type, age, health);
    }

    public Bee anotherDay(){
        return this;
    }

        public boolean eat(){
   -->         if(hive.honey > 2){
                hive.takeHoney(2); 
                return true;
            }else{
                return false;
            }   
        }
} 

您是靜態地引用Hive。 您需要實例化它,然后在該對象上調用方法。

public class Queen extends Bee{

int type = 1;
Hive h;
public Queen(Hive hive){

    h = hive;


}

public Queen(int type, int age, int health){
    super(type, age, health);
}

public Bee anotherDay(){
    return this;
}

public boolean eat(){
    if(h.honey > 2){
        h.takeHoney(2);
        return true;
    }else{
        return false;
    }   
}

}

這絕對不會做任何事情:

public Queen(Hive hive){

}

您在哪里將其分配給班級中的某個字段? 回答你不。

解決方案:應該!

public Queen(Hive hive){
  this.hive = hive;
}

當然也要給女王一個叫做蜂巢的領域。 這樣您就可以使用它了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM