开发者

Problems understanding static modifier

开发者 https://www.devze.com 2023-04-04 16:20 出处:网络
I am having difficulty understanding what a \"static\" method and \"static\" variable is and it is causing me p开发者_Go百科roblems with my code. Here is the code I am having difficulty with:

I am having difficulty understanding what a "static" method and "static" variable is and it is causing me p开发者_Go百科roblems with my code. Here is the code I am having difficulty with:

    public class Document{
      public void NewBlank(){
           Resources.openRawResource(R.raw.blank);
           }
       }

Why do I get the error "Cannot make a static reference to the non-static method Resource.openRawResource(int) from the type Resources"? Why can't I reference a non-static method?


openRawResources is not a static method, it needs to be invoked in an object, not a type. In order to get an instance of Resources you could call getResources in an activity. Then the resulting code would be

Resources resources = myactivity.getResources();
resources.openRawResource(R.raw.blank);

A static method/variable is one that belongs to the class type, and not to the instances/objects of such type.


Cannot make a static reference to the non-static method

This means that for invoking that method you are trying to, you need a reference to an instance of that class. Here's an example illustrating the difference:

public class Foo{
     public static int staticVariable = 5;
     public static void methodStatic(){}
     public void nonStaticMethod(){}
}

here's how you can use them:

Foo.nonStaticMethod(); //can call static method referring to the class itself without having an instance

Foo f = new Foo();
f.nonStaticMethod(); //you need an instance of a Foo class in order to call a non-static method

For what concern static variables, these are variables that doesn't belong to a single instance of a class, but are shared between all different instances of the same class:

Foo a = new Foo();
Foo b = new Foo();

System.out.println(a.staticVariable); //print 5
System.out.println(b.staticVariable); //print 5

a.staticVariable = 10;
System.out.println(b.staticVariable); //print 10

(Please, look at the example above just to understand the concept of what a static variable is. You'll get the warning "access a static field in a non-static way" because that's not a proper way to access those variables)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号