2012-05-03 133 views
1

我正在製作一個小型遊戲,其中Main類包含所有對象和變量,並調用大部分工作的類本身內的方法。相當標準。不幸的是,這意味着我需要的許多變量都在Main類中,我無法訪問它們。例如,作爲一個測試,我想要一個球在屏幕上反彈,很簡單,但我需要屏幕的尺寸,我可以在主類中使用getSize()方法輕鬆獲得。但是當我創建會反彈的Ball類時,我無法訪問getSize()方法,因爲它在Main類中。無論如何要打電話嗎?Java訪問主類變量

我知道我可以在構造函數或每個我需要的方法中將變量傳遞給Ball類,但我想知道是否有某種方法可以在需要時使用我需要的變量,而不是傳遞無論什麼時候我創造一個新的物體,它都是這些信息

Main.class

public void Main extends JApplet { 
    public int width = getSize().width; 
    public int height = getSize().height; 

    public void init(){ 
     Ball ball = new Ball(); 
    } 
} 

Ball.class

public void Ball { 
    int screenWidth; 
    int screenHeight; 

    public Ball(){ 
     //Something to get variables from main class 
    } 
} 

回答

1

傳給你需要你的對象變量。你甚至可以創建一個包含你的類需要的所有常量/配置的單例類。

實施例給出:

Constants類

public class Constants { 
    private static Constants instance; 

    private int width; 
    private int height; 

    private Constants() { 
     //initialize data,set some parameters... 
    } 

    public static Constants getInstance() { 
     if (instance == null) { 
      instance = new Constants(); 
     } 
     return instance; 
    } 

    //getters and setters for widht and height... 
} 

Main類

public class Main extends JApplet { 
    public int width = getSize().width; 
    public int height = getSize().height; 

    public void init(){ 
     Constants.getInstance().setWidth(width); 
     Constants.getInstance().setHeight(height); 
     Ball ball = new Ball(); 
    } 
} 

Ball類

public class Ball { 
    int screenWidth; 
    int screenHeight; 

    public Ball(){ 
     this.screenWidth = Constants.getInstance().getWidth(); 
     this.screenHeight= Constants.getInstance().getHeight(); 
    } 
} 

的另一種方式可以是與所述PARAM啓動對象實例讓你需要。給出的例子:

主要類

public class Main extends JApplet { 
    public int width = getSize().width; 
    public int height = getSize().height; 

    public void init(){ 
     Ball ball = new Ball(width, height); 
    } 
} 

Ball類

public class Ball { 
    int screenWidth; 
    int screenHeight; 

    public Ball(int width, int height){ 
     this.screenWidth = width; 
     this.screenHeight= height; 
    } 
} 

有更多的方式來實現這一目標,就看出來你自己,並選擇你認爲它會爲你的項目更好的一個。

+0

真棒,這正是我一直在尋找。現在每個類都可以訪問常量中的變量,而不必每次都傳遞它們。非常感謝。 – Doug

1

只需使用兩個參數構造函數即可訪問它們。

public void init(){ 
     Ball ball = new Ball(width,height); 
    } 

public Ball(width,height){ 
     //access variables here from main class 
    } 
0

爲什麼不這樣說:

public void Main extends JApplet { 
public int width = getSize().width; 
public int height = getSize().height; 

public void init(){ 
    Ball ball = new Ball(width, height); 
} 


public void Ball { 

public Ball(int screenWidth, int screenHeight){ 
    //use the variables 
}