简体   繁体   中英

Instance variables in static method

I'm preparing the OCA certification for Java SE 7 and during the first chapter Java Basics , I read the following things about static methods:

Static methods aren't associated with objects and can't use any of the instance variable of a class.

In the following example the compiler gives me an error:

class MyClass2 {

    String a;

    public MyClass2() {

    }

    static void check(){
        if (a.equals("TEST"))
            return; 
    }
}

Cannot make a static reference to the non-static field a.

If I change the class definition in this way:

class MyClass {

    String a;

    public MyClass() {
        // TODO Auto-generated constructor stub
        check(a);
    }

    static void check(String a){
            if (a.equals("TEST"))
                return; 
    }
}

everything works and the compiler doesn't show any error, which is strange because a is always an instance variable.

In the second example, you check has a parameter called a . The equality check is performed against it, and not against the instance member a which is, indeed, still inaccessible from a static context.

A static method can only refer to static variables. As non static variables do not belong to the class, but to specific objects that are instantiated... there is no way for a static method to know which of the variables to show. For example you create two instances of MyClass

MyClass x,y;
x.a =10;
x.b=20;

Then there is no way to know which one is right one to pick from static function as Static function is not associated with any specific instance (x or y).

So in case you want to access variable a you need to declare it as static.

static String a;

BUT , in your second case you have a as parameter, so as the parameter is being referred in place of the class level variable there is no error. In case you want error use this.a to refer to class level variable.

In first case while compilation error occurred -

  • you have a non static filed String a
  • you are trying to access the String a from you static method check()

That's why the compilation error occurred

And in second case while no compilation error occurred -

  • You are calling your static method check() from your constructor MyClass() .
  • It is completely valid to call a static method of a class without creating it's instance/object.
    And that's why you are not getting any compilation error.

Hope it will help you.
Thanks a lot.

When you pass an instance variable to a static method (or any other method for that matter) you pass the value of that variable. Not the variable itself. That's probably why you are not getting error. The variable itself however, doesn't become available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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