Jump to content

non-static method cannot be referenced from a static context

Claryn
Go to solution Solved by Philosobyte,

I explained this somewhat in your other thread. 

 

The problem here is you're not understanding the most important, foundational concept in OOP. And that's the difference between a class and an object. 

 

A class is a definition of something, and an object is an instance of something. Classes can only use class methods, and not instance methods. meanwhile, objects can use both class methods and instance methods (but in my opinion should stick with using only instance methods). 

 

 For example, let's say we have this class and these objects:

 

class Human: the definition of a certain species of bipedal organism which has high intelligence and refined motor skills. 

objects Mary, Jane, and Watson: each of these three objects is an instance of Human. Each of these objects are created from the definition Human. 


These two types are not interchangeable - neither in real life nor in Java. There are going to be methods which can only be carried out by the Human definition (or the "entire Human race") and there are methods which can only be carried out by individual humans. This is seen in the following example code. 

 

public class Human {
    //1 - class variables (also known as static variables)
    static double averageHeight = 177.8;
    static double averageWeight = 141.53;
    static double maxRunningSpeed = 44.2;
    static long populationCount = 7000000000L;

    //2 - instance variables
    double height;
    double weight;
    double runningSpeed;
    String name;

    public Human(String name, double height, double weight, double runningSpeed) {
        this.name = name;
        this.height = height;
        this.weight = weight;
        this.runningSpeed = runningSpeed;
    }

    //3 - instance method
    public void run() {
        System.out.println(name + " is running at " + runningSpeed + " km/hr.");
    }

    //4 - class method (also known as static method)
    public static void goThroughExtinction() {
        populationCount = 0;
        System.out.println("Oh noes! It appears that the human race is no more.");
    }
}

public class Main {

    public static void main(String[] args) {
        Human Mary = new Human("Mary", 163, 156, 13);
        Human Jane = new Human("Jane", 166, 141, 19);
        Human Watson = new Human("Watson", 172, 185, 32);

        Human.run(); //5 - Static context error
        Watson.run();

        Human.goThroughExtinction();
        Mary.goThroughExtinction(); //6 - no error, but avoid this
    }
}

1: Class variables apply to not any one object in particular, but all objects. In this case, the average height, weight, and top running speed apply to the entire Human species.

 

2: Instance variables apply to a single object and do not necessarily represent the class. In this case, a single person's height and weight doesn't represent the height and weight of the entire Human species.

 

3 and 5: An instance method is an action which can only be carried out by an individual object, not a class. You can say that a single person such as Watson ran at a speed of 32 km/hr, but it doesn't make sense to say "the entire human species ran at a speed of 32 km/hr." The entire human species isn't a thing that can run; only members of the human species can run. That's why you're getting a static context error. You're trying to make a class execute an instance method like I'm trying to make the human species run, and that isn't possible.

 

4 and 6. A class method is an action which should only be carried out by the class, not the object. The entire human species can go through extinction and die off, but it doesn't make sense to say "Mary went through extinction." A single person can't go "extinct." Despite this, Java allows you to use an object to execute a class method. So even though it doesn't make sense to say that Mary went through extinction, Java allows you to do it. 

 

-------------------------------------------------------------------------------

 

So how does this apply to you? Well, first of all, what I just explained is the entire point of Object-Oriented Programming (OOP) languages such as Java. If you don't completely understand this concept, you won't be progressing very far in Java. 

 

Second of all, points 3 and 5 explain the error you described in your original post. If you consider that

 

1. classes can't execute instance methods

2. playGame is a class

3. #startNewGame is an instance method

 

it follows logically that playGame can't execute #startNewGame. That line of code in your original post won't work. Instead, you have to create a playGame, like this:

playGame game = new playGame();
game.startNewGame();

In this case game is an object. Since instance methods are meant to be used with objects, you won't get an error here. 

 

In my opinion, though your overall class/method structure is convoluted and doesn't make sense OOP-wise. A class should be a definition, a "class" of objects, while a method should be an action, a thing you can do. Your structure does not follow this principle because one of your classes is named "play game," which is an action instead of a definition. 

Hi.

 

So I am about to wrap up a larger project, and figured there are some strange bugs in my code. 

There are a couple of method-calls that gives me the error:
"non-static method blahblah cannot be referenced from a static context".

 

Now the problem is that the method that calls the non-static method is non-static. I don't understand why it would say the non-static method is being referenced from a static context.

 

So I have a jFrame that includes the method newGame()

which looks as follows:
 

    public void startNewGame()
    {
        
       String input; 
       int numPlayers = 0;
       
       do
       {
            input = JOptionPane.showInputDialog("How many players are you? (3-6)");
            numPlayers = Integer.parseInt(input);
            if (numPlayers<3)
            {
                 JOptionPane.showMessageDialog(null, "Error"
                 + "", "You must be at least 3 players!", JOptionPane.ERROR_MESSAGE);
             }
             else if (numPlayers>6)
             {
                 JOptionPane.showMessageDialog(null, "Error"
                 + "", "You can't be more than 6 players!", JOptionPane.ERROR_MESSAGE);       
             } 
       }
       while (numPlayers<3 && numPlayers>6);

       numOfPlayers.setText("numPlayers");

		// this is the line that causes the error:
       playGame.startNewGame(numPlayers);
    }

the startNewGame method that is bering referenced, is in the playGame class, and it looks like this:
 

    public void startNewGame(int numPlayers)
    {
        players = new cahPlayer[numPlayers];
        
        for (int i = 0; i < numPlayers; i++)
        {
            players[i] = new cahPlayer(i, this);
        }
        
        setDealer(numPlayers);
        initialDealing(numPlayers);
        cahUI.scoreP1.setText(Integer.toString(0));
        cahUI.scoreP2.setText(Integer.toString(0));
        cahUI.scoreP3.setText(Integer.toString(0));
        cahUI.scoreP4.setText(Integer.toString(0));
        cahUI.scoreP5.setText(Integer.toString(0));
        cahUI.scoreP6.setText(Integer.toString(0));
        
    }

 

None of them are static. What is the problem here? 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

static classes can't have non-static methods or members

 

since they can't be instantiated, only 1 object of that class can exist. So even if in theory you could declare an instance member, you'd never be able to access it.

 

I also don't know why you're using the same method name in different classes, that just sounds like a recipe for confusion. Why not name the first method checkPlayerCount or something?

 

My guess would be that your game class is static, which would make sense. It would let you access the same object regardless of where in the code you where.

 

    public static void startNewGame(int numPlayers)
Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, MrBucket101 said:

static classes can't have non-static methods or members

 

since they can't be instantiated, only 1 object of that class can exist. So even if in theory you could declare an instance member, you'd never be able to access it.

 

I also don't know why you're using the same method name in different classes, that just sounds like a recipe for confusion. Why not name the first method checkPlayerCount or something?

 

My guess would be that your game class is static, which would make sense. It would let you access the same object regardless of where in the code you where.

 


    public static void startNewGame(int numPlayers)

I am not sure if I understood what you meant by that. If I change the method to static, like you did, I get a billion other errors inside that method because it is using a bunch of non-static variables (which are defined as static).

When changing the playGame.startNewGame to static, I still get the same error in the cahUI.startNewGame method. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Claryn said:

I am not sure if I understood what you meant by that. If I change the method to static, like you did, I get a billion other errors inside that method because it is using a bunch of non-static variables (which are defined as static).

When changing the playGame.startNewGame to static, I still get the same error in the cahUI.startNewGame method. 

Basically, you've got a static class somewhere. Either it needs to be static, and you make its methods and members static as well, or it needs to be an instance class, (which can have static members)

 

I'd just do a ctrl+f of your project and look for the word static, maybe you'll find the rogue declaration

 

https://msdn.microsoft.com/en-us/library/aa645629(v=vs.71).aspx maybe this will help

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, MrBucket101 said:

Basically, you've got a static class somewhere. Either it needs to be static, and you make its methods and members static as well, or it needs to be an instance class, (which can have static members)

 

I'd just do a ctrl+f of your project and look for the word static, maybe you'll find the rogue declaration

 

https://msdn.microsoft.com/en-us/library/aa645629(v=vs.71).aspx maybe this will help

Okay in the playGame class, I have the startNewGame method as I showed.

In the playGame class, I am making instances of a jFrame called cahPlayer. Might this be the problem? Becuase as I said, now that I have declared the method to be static, I still get the same error in the other startNewGame method that referenced the method in the playGame class.

 

It looks like this:
 

public class playGame {
    
    public static cahPlayer[] players;
    public int currentDealerID;
    
    
    public static void startNewGame(int numPlayers)
    {
        // set up the array
        players = new cahPlayer[numPlayers];
        
        // setting up the amount if windows we want
        for (int i = 0; i < numPlayers; i++)
        {
            players[i] = new cahPlayer(i, this);
        }
        
        setDealer(numPlayers);
        initialDealing(numPlayers);
        cahUI.scoreP1.setText(Integer.toString(0));
        cahUI.scoreP2.setText(Integer.toString(0));
        cahUI.scoreP3.setText(Integer.toString(0));
        cahUI.scoreP4.setText(Integer.toString(0));
        cahUI.scoreP5.setText(Integer.toString(0));
        cahUI.scoreP6.setText(Integer.toString(0));
        
    }

 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

Are setDealer, initialDealing and cahUI all static?

What line is it telling you the error is on?

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, fizzlesticks said:

Are setDealer, initialDealing and cahUI all static?

What line is it telling you the error is on?

I have tried to make all methods in the playGame class to be static. That give me 1 error in the startNewGame method: 

 

players[i] = new cahPlayer(i, this);

Then I receive the error mentioned in other classes' methods that tries to reference any method in the playGame method.

There is also a third class (jFrame) that gets the same error when referecing the cahUI.startNewGame method that is referencing the playGame.startNewGame method. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, MrBucket101 said:

My guess would be the playgame class needs to be static

Then it just tells me:
modified static not allowed here

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

players[i] = new cahPlayer(i, this);

You can't use "this" in a static method. this refers to the object you're inside of, which doesn't make sense inside of a static method.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, fizzlesticks said:

players[i] = new cahPlayer(i, this);

You can't use "this" in a static method. this refers to the object you're inside of, which doesn't make sense inside of a static method.

Well I have to, because my instances of the cahPlayer class is dependent on it. Then I just need a solution for being able to reference non-static methods in the playGame class from other classes. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Claryn said:

Well I have to, because my instances of the cahPlayer class is dependent on it. Then I just need a solution for being able to reference non-static methods in the playGame class from other classes. 

Well actually I can leave out this, but even though all the methods are static, I get the same errors when referencing them from other classes. That is the issue I need to solve. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

I explained this somewhat in your other thread. 

 

The problem here is you're not understanding the most important, foundational concept in OOP. And that's the difference between a class and an object. 

 

A class is a definition of something, and an object is an instance of something. Classes can only use class methods, and not instance methods. meanwhile, objects can use both class methods and instance methods (but in my opinion should stick with using only instance methods). 

 

 For example, let's say we have this class and these objects:

 

class Human: the definition of a certain species of bipedal organism which has high intelligence and refined motor skills. 

objects Mary, Jane, and Watson: each of these three objects is an instance of Human. Each of these objects are created from the definition Human. 


These two types are not interchangeable - neither in real life nor in Java. There are going to be methods which can only be carried out by the Human definition (or the "entire Human race") and there are methods which can only be carried out by individual humans. This is seen in the following example code. 

 

public class Human {
    //1 - class variables (also known as static variables)
    static double averageHeight = 177.8;
    static double averageWeight = 141.53;
    static double maxRunningSpeed = 44.2;
    static long populationCount = 7000000000L;

    //2 - instance variables
    double height;
    double weight;
    double runningSpeed;
    String name;

    public Human(String name, double height, double weight, double runningSpeed) {
        this.name = name;
        this.height = height;
        this.weight = weight;
        this.runningSpeed = runningSpeed;
    }

    //3 - instance method
    public void run() {
        System.out.println(name + " is running at " + runningSpeed + " km/hr.");
    }

    //4 - class method (also known as static method)
    public static void goThroughExtinction() {
        populationCount = 0;
        System.out.println("Oh noes! It appears that the human race is no more.");
    }
}

public class Main {

    public static void main(String[] args) {
        Human Mary = new Human("Mary", 163, 156, 13);
        Human Jane = new Human("Jane", 166, 141, 19);
        Human Watson = new Human("Watson", 172, 185, 32);

        Human.run(); //5 - Static context error
        Watson.run();

        Human.goThroughExtinction();
        Mary.goThroughExtinction(); //6 - no error, but avoid this
    }
}

1: Class variables apply to not any one object in particular, but all objects. In this case, the average height, weight, and top running speed apply to the entire Human species.

 

2: Instance variables apply to a single object and do not necessarily represent the class. In this case, a single person's height and weight doesn't represent the height and weight of the entire Human species.

 

3 and 5: An instance method is an action which can only be carried out by an individual object, not a class. You can say that a single person such as Watson ran at a speed of 32 km/hr, but it doesn't make sense to say "the entire human species ran at a speed of 32 km/hr." The entire human species isn't a thing that can run; only members of the human species can run. That's why you're getting a static context error. You're trying to make a class execute an instance method like I'm trying to make the human species run, and that isn't possible.

 

4 and 6. A class method is an action which should only be carried out by the class, not the object. The entire human species can go through extinction and die off, but it doesn't make sense to say "Mary went through extinction." A single person can't go "extinct." Despite this, Java allows you to use an object to execute a class method. So even though it doesn't make sense to say that Mary went through extinction, Java allows you to do it. 

 

-------------------------------------------------------------------------------

 

So how does this apply to you? Well, first of all, what I just explained is the entire point of Object-Oriented Programming (OOP) languages such as Java. If you don't completely understand this concept, you won't be progressing very far in Java. 

 

Second of all, points 3 and 5 explain the error you described in your original post. If you consider that

 

1. classes can't execute instance methods

2. playGame is a class

3. #startNewGame is an instance method

 

it follows logically that playGame can't execute #startNewGame. That line of code in your original post won't work. Instead, you have to create a playGame, like this:

playGame game = new playGame();
game.startNewGame();

In this case game is an object. Since instance methods are meant to be used with objects, you won't get an error here. 

 

In my opinion, though your overall class/method structure is convoluted and doesn't make sense OOP-wise. A class should be a definition, a "class" of objects, while a method should be an action, a thing you can do. Your structure does not follow this principle because one of your classes is named "play game," which is an action instead of a definition. 

Link to comment
Share on other sites

Link to post
Share on other sites

On 28 February 2016 at 1:44 AM, Philosobyte said:

snip

Thank you very much. This helped me understand instanced methods better, but I still think I'll need to go back and read some more on it!

I managed to solve my problem, so that is good :) Thank you very much. 

Running Arch with i3-gaps on a Thinkpad X1 Extreme
Data Science Postgrad

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×