简体   繁体   English

如何从静态调用非静态方法?

[英]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(); 我试图从静态calldrawScore()调用非静态drawScore()方法,但我得到了错误"cannot find symbol constructor Game"在线Game draw = new Game(); in calldrawScore() . calldrawScore() When I pass with mouse over that line it says "GameScreen (Game) in Game cannot be applied to ()" . 当我用鼠标"GameScreen (Game) in Game cannot be applied to ()"过该行时,它说"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. -这是因为static member属于class ,其中作为non-static成员属于object ,所以作为该静态成员试图访问一个非静态成员它不会清楚的是哪些对象构件正被访问,所以其JAVA禁止。

Maybe if you can change "getScore(int x)" into: 也许你可以将“getScore(int x)”改为:

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

and now you can call it in "GameScree" by 现在你可以在“GameScree”中调用它

GameScreen.getScore(valueSome, yourObject);

Another way is to change all GameScreen into Singleton 另一种方法是将所有GameScreen更改为Singleton

Your class GameScreen constructor is taking Game class object as a parameter. 您的GameScreen类构造函数将Game类对象作为参数。 You can either get the current Game instance and pass it as a argument or create a default constructor in your Gamescreen class. 您可以获取当前的Game实例并将其作为参数传递,也可以在Gamescreen类中创建默认构造函数。

To do GameScreen d = new GameScreen() you need to have 0-argument constructor for GameScreen . 要做GameScreen d = new GameScreen()你需要为GameScreen提供0参数构造GameScreen You don't have such constructor. 你没有这样的构造函数。

Anyway, your code looks preety bad, because you are creating new GameScreen in every calldrawScore() ... 无论如何,你的代码看起来很糟糕,因为你在每个calldrawScore()中都在创建新的GameScreen ...

I think you need to read what's the difference between static and non-static methods. 我想你需要阅读静态方法和非静态方法之间的区别。 Then go back, design it and implement better. 然后返回,设计并更好地实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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