user1462183
user1462183

Reputation:

Misunderstanding in Java

I'm trying the static and non-static methods and fields. I tried to compile this:

class main{
    public int a=10;
    static int b=0;
    public static void main(String[] args){
        b+=1; //here i can do anything with static fields.
    }
}

class bla {
    void nn(){
        main.a+=1; //why here not? the method is non-static and the field "main.a" too. Why?
    }
}

and the compiler returns me:

try.java:10: non-static variable a cannot be referenced from a static context

but why? The method and the field "a" are both non-static!

Upvotes: 2

Views: 146

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347334

The variable a is NOT static and thus can not be accessed without an instance of Main

Main.b += 1; // This will work, assuming that your class is in the same package

Main main = new Main();
main.a += 1; // This will work because we can reference the variable via the object instance

So, lets assume we have the class

public class Main {

    public int a = 10;
    static int b = 0;

}

Now we come along with, assuming that the classes are in the same package

public class Blah {

    void nn() {

        Main.a += 1; // This will fail, 'a' is not static
        Main.b += 1; // This is fine, 'b' is static

        Main main = new Main();
        main.a += 1; // Now we can access 'a' via the Object reference

    }
}

Upvotes: 2

nicholas.hauschild
nicholas.hauschild

Reputation: 42834

You are attempting to access a in a static manner. You will first need to instantiate main to access a.

main m = new main();
m.a += 1;

Also, for readability, you should capitalize the names of Classes, and camel case your instance variables.

Upvotes: 2

Justin Skiles
Justin Skiles

Reputation: 9523

You have not initialized an instance of main in the nn() method.

Upvotes: 0

Calvin Jia
Calvin Jia

Reputation: 856

You need an instance of class main to change a since that is not a class variable.

Upvotes: 0

Related Questions