Here is the code

Java

class method

{

    int counter = 0;

    public static void main(String[] args)

    {

        System.out.println(counter);

    }

}

It gave me this error.

Main.java:6: error: non-static variable counter cannot be referenced from a static context

        System.out.println(counter);

How do I make it recognize the variables of the class?


If you want to unleash your potential in this competitive field, please visit the Java course page for more information, where you can find the Java tutorials and Java frequently asked interview questions and answers as well.

1
Answers

Replies

The solution is that you either make your fields static or your methods non static. It would look like below:


class Programm {



    public static void main(String[] args) {


        Programm programm = new Programm();


        programm.start();


    }



    public void start() {


        // can now access non-static fields


    }


}

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
WhatsApp
To Top