声明实例变量以引用对象

时间:2015-01-19 21:06:46

标签: java object instance-variables japplet

所以我们正在制作游戏的头像,我们已经将头像创建为Avatar类文件。我们的问题是,在我们的类文件Game中,我们很难将Avatar声明为实例变量。 代码如下:

public class Game extends JApplet {
    private static final long serialVersionUID = 1L;
    public static final long WIDTH = 800;
    public static final long HEIGHT = 600;

    // Declare an instance variable to reference your Avatar object

    public @Override void init() {
        // Store an instantiated Avatar into the instance variable
        setSize(new Dimension( WIDTH, HEIGHT));
        getContentPane().setBackground(Color.BLUE); 
    }

    public @Override void paint(Graphics g) { 
        super.paint(g); // Call the JAplet paint method (inheritance)
        // Call the draw method in your Avatar class
    }
}  

1 个答案:

答案 0 :(得分:0)

你可以尝试:

private Avatar avatar;

avatar = new Avatar();

avatar.draw();

像这样:

public class Game extends JApplet {
private static final long serialVersionUID = 1L;
public static final long WIDTH = 800;
public static final long HEIGHT = 600;

// Declare an instance variable to reference your Avatar object
private Avatar avatar;


public @Override void init() {
    // Store an instantiated Avatar into the instance variable
    avatar = new Avatar();

    setSize(new Dimension( WIDTH, HEIGHT));
    getContentPane().setBackground(Color.BLUE); 
}

public @Override void paint(Graphics g) { 
    super.paint(g); // Call the JAplet paint method (inheritance)
    // Call the draw method in your Avatar class

    avatar.draw(); //replace "draw" with method you want to invoke :)
    }
}