简体   繁体   中英

How to call non-static method from static?

I tried to call non-static drawScore() method from static calldrawScore() , but I got the error "cannot find symbol constructor Game" on line Game draw = new Game(); in calldrawScore() . When I pass with mouse over that line it says "GameScreen (Game) in Game cannot be applied to ()" .

- Its rule of thumb that a static method can't access any non-static variable or methods .

- It is because static member belongs to the class where as non-static members belongs to the object , so as the static member tries to access a non-static member it won't be clear that which objects member is being accessed, so its prohibited in JAVA.

Maybe if you can change "getScore(int x)" into:

public static int getScore(int x, GameScreen gs) {
        score = x;
        gs.drawScore();
        return score;
    }

and now you can call it in "GameScree" by

GameScreen.getScore(valueSome, yourObject);

Another way is to change all GameScreen into Singleton

Your class GameScreen constructor is taking Game class object as a parameter. You can either get the current Game instance and pass it as a argument or create a default constructor in your Gamescreen class.

To do GameScreen d = new GameScreen() you need to have 0-argument constructor for GameScreen . You don't have such constructor.

Anyway, your code looks preety bad, because you are creating new GameScreen in every calldrawScore() ...

I think you need to read what's the difference between static and non-static methods. Then go back, design it and implement better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM