2

Main クラスがすべてのオブジェクトと変数を保持し、ほとんどの作業を行うクラス内のメソッドを呼び出す小さなゲームを作成しています。かなり標準的。残念ながら、これは必要な変数の多くがアクセスできない Main クラスにあることを意味します。

たとえば、テストとして、ボールを画面上で跳ね返らせたいと思っていましたが、これは簡単なことですがgetSize()、メイン クラスのメソッドを使用して簡単に取得できる画面の寸法が必要です。しかし、バウンスするクラスを作成すると、クラス内にあるため、メソッドにBallアクセスできません。とにかくそれを呼び出すことはありますか?getSize()Main

コンストラクター内のクラスまたは必要なメソッドごとに変数を渡すことができることはわかっていますが、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();
    }
}

ボールクラス

public void Ball {
    int screenWidth;
    int screenHeight;

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

3 に答える 3

3

必要な変数をオブジェクトに渡します。クラスに必要なすべての定数/構成を含むシングルトン クラスを作成することもできます。

例:

定数クラス

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...
}

メインクラス

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();
    }
}

ボールクラス

public class Ball {
    int screenWidth;
    int screenHeight;

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

もう 1 つの方法は、必要なパラメーターを使用してオブジェクト インスタンスを開始することです。例:

メインクラス

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

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

ボールクラス

public class Ball {
    int screenWidth;
    int screenHeight;

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

これを達成する方法は他にもあります。自分自身をよく見て、自分のプロジェクトに適していると思われる方法を選択してください。

于 2012-05-03T06:06:49.193 に答える
1

単純に 2 つの arg コンストラクターを使用してそれらにアクセスできます。

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

public Ball(width,height){
        //access variables here from main class
    }
于 2012-05-03T06:07:34.853 に答える
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
}
于 2012-05-03T06:10:18.963 に答える