2012-02-23 95 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) 
相關問題