2017-01-12 83 views
-19

例如:我如何從一個類訪問一個int變量? (JAVA)

在一級

int killcount = 0; 

在二班

killcount = 5; 

所有我想做的事,我從一個得到變量班到另一班。我會怎麼做?

+2

谷歌有關實例,定居者和獲得者... –

+4

你可以d o通過學習Java的基礎知識。或通過在互聯網上或在這裏搜索。這已被問及許多次。 – Tom

+5

這是一個非常基本的東西,你問,通常通過創建公共getter方法來解決。請注意,反對是因爲你在提出問題之前缺乏關於此主題的論證研究工作,而且本網站不應被用來替代你研究語言的基本基礎。 –

回答

2

在嘗試使用Bukkit之前,我建議您先獲得一些Java體驗。這並不意味着是一種侮辱,但如果你反過來這樣做會變得相當混亂。無論如何,如果你仍然想知道你的問題的答案:

你必須爲你的「killcount」變量創建一個getter & setter。

class Xyz { 

    private int killcount; 

    public void setKillcount(int killcount) { 
     this.killcount = killcount; 
    } 

    public int getKillcount() { 
     return this.killcount; 
    } 

} 

當然,這是不檢查一個簡化版本,但如果你想從不同的類訪問變量,您可以創建一個實例,並使用方法進行修改。

public void someMethod() { 

    Xyz instance = new Xyz(); 
    instance.setKillcount(instance.getKillcount() + 1); 
    //this would increase the current killcount by one. 

} 

記住,如果你想保持你的價值觀,爲創建一個新的將重置它們爲默認,你必須使用類的同一個實例。因此,您可能也想將其定義爲私有變量。

0

考慮例子

public class Test { 
    public int x = 0; 
} 

這個變量x可以在其他類像

public class Test2 { 
    public void method() { 
     int y = new Test().x; 
     // Test.x (if the variable is declared static) 
    } 
} 

理想的情況下被訪問,實例變量是由私人和getter方法暴露訪問它們

public class Test { 
    private int x = "test"; 
    public int getX() { 
     return x; 
    } 
    public void setX(int y) { 
     x = y; 
    } 

} 
相關問題