0

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 ()".

user2668638
  • 653
  • 1
  • 7
  • 9
  • To call a non-static method you need an instance of the class the method expect. If you have this, you can call it anywhere. – Peter Lawrey Sep 10 '13 at 09:36
  • Remember in OOP static means its a Class method as no-static means its an Instance method. – enkor Sep 10 '13 at 09:43
  • possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – user207421 Sep 10 '13 at 09:44

4 Answers4

2

- 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.

nidhi
  • 763
  • 5
  • 17
  • 2
    You can access a non static method from static method by creating an instance in the static method. – Code Enthusiastic Sep 10 '13 at 09:45
  • @CodeEnthusiastic you are right about it, thats one way of defining a singleton principle, but as far as i know, there is no direct way of accessing a non-static member from a static member and was something i wanted the OP to know, but thanks for providing another angle to this answer. – nidhi Sep 10 '13 at 10:42
0

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

Community
  • 1
  • 1
Dariusz Mazur
  • 587
  • 5
  • 21
0

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.

prijupaul
  • 2,076
  • 2
  • 15
  • 17
0

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.

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110