2012-05-03 131 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 
}