2012-02-23 86 views
-1

Possible Duplicate:
What is the reason behind “non-static method cannot be referenced from a static context”?非静态方法不能从静态上下文中引用?

我有以下方法:

public void fillMachine(Game game) 
{ 
    // Colours of balls are evenly spread between these colours, 
    // in ascending order. 
    Color [] colourGroupColours 
    = new Color [] {Color.red, Color.orange, Color.yellow, 
        Color.green, Color.blue, Color.pink, 
        Color.magenta}; 
    // This happiness change will show up when the GUI is added. 

    Color ballColour; 
    int noOfBalls = game.getMachineSize(); 
    for (int count = 1; count <= noOfBalls; count++) 
    { 
    // The colour group is a number from 0 
    // to the number of colour groups - 1. 
    // For the nth ball, we take the fraction 
    // (n - 1) divided by the number of balls 
    // and multiply that by the number of groups. 
    int colourGroup = (int) ((count - 1.0)/(double) noOfBalls 
          * (double) colourGroupColours.length); 
    ballColour = colourGroupColours[colourGroup]; 
    game.machineAddBall(makeNewBall(count, ballColour)); 
    } // for 

    } // fillMachine 

在主类我有fillMachine(game1);

我收到错误:non-static method fillMachine(Game) cannot be referenced from a static context fillMachine(game1);

我不知道如何解决这虽然。

+0

这里有没有问题? – ewok 2012-02-23 19:44:03

+0

将static添加到您的方法 – VirtualTroll 2012-02-23 19:45:21

回答

2

这是因为您无法从static方法访问非静态成员。 (除非您有一个对象调用该方法)

您的main方法是静态的。这意味着它不是绑定到一个类的特定对象,而是绑定到类本身。 fillMachine不是静态的,这意味着您只能在类的具体实例上调用它。你没有的。你可以:

  • 使方法static,如果你没有使用它的任何非静态成员。
  • 创建一个对象,并调用该方法的实例
+4

您当然可以* *您只需要一个实例就可以调用*上的member *。 – 2012-02-23 19:45:13

+1

@JonSkeet:漂亮的挑选。 – Kevin 2012-02-23 19:46:57

+0

需要挑选nit! – 2012-02-23 20:10:04

2

你还没有真的在这里给了我们很多方面,但基本上你的方法是实例的方法,所以对一个实例被称为。你可以从静态方法调用它,但你需要有一个实例来调用它。例如:

Foo foo = new Foo(); // We don't know what class this is in... you do. 
foo.fillMachine(game1); 

当然,你可能已经有您在别处创建的类的实例,而且可能是适当的实例来调用方法。

或者,如果不需要引用任何实例变量,则可以使该方法为静态。

了解静态成员(这是关系到类,而不是类的任何特定实例)和实例成员(这些都与一个特定的实例)之间的区别是很重要的。

查看Java Tutorial了解更多信息。

+1

man.You是一个人类机器人。 – 2012-02-23 19:47:20

0

只是改变

public void fillMachine(Game game) 

public static void fillMachine(Game game) 
相关问题