communication between static method and instance field in java
"Static methods may not communicate with instance fields, only static fields". I got to read this quoted lines. When I studied other threads in this forum, I found that we开发者_开发问答 can use instance fields in static methods and vice versa. So, what does this quote means?? Is it true?
You can't use non-static (instance) fields in static method. That's because a static method is not associated with an instance.
A static
method is one-per-class, while a class may have many instances. So if you have 2 instances, the fields of which one will the static methods see?
Let's imagine that this is valid:
class Foo {
private int bar;
public static int getBar() {
return bar; // does not compile;
}
}
And then:
Foo foo1 = new Foo();
foo1.bar = 1;
Foo foo2 = new Foo();
foo2.bar = 2;
Foo.getBar(); // what would this return. 1 or 2?
class MyClass{
int i ;
static String res;
public static void myMethod(){
i = 10 //not allowed because it is instance non static field
res = "hello" ; allowed , because it is static field
new MyClass().i = 10;//allowed as we are accessing it using an instance of that class
}
}
Description: Static fields/methods/.. are associated with class not with object of that class. where member variable/methods are associated with class's object so to access them we need object of class
Also See
- Documentation
You can't use instance fields in a static method. Which instance are you referring to ?
However a static method may have a reference to an instance, and thus use the fields on that instance.
e.g.
public class Stock {
public double price = 0.0;
public static void setPriceIncorrectly() {
price = 0.0 // which price ?
}
public static void setPriceCorrectly() {
Stock s = new Stock();
s.price = 0.0 // which price ?
}
}
I found that we can use instance fields in static methods and vice versa
That isn't true; you can't refer to instance fields in "static" methods because "static" methods don't belong to an "instance".
Recommended reading: http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
You can't use something that do not exists.
When You have static field or method is not associated with an instace. so the non static elements does not exists.
You always need an instance to communicate with instance fields. If you have access to an instance (e.g. param or static field) you can access their members. But you cannot access instance fields of the class directly.
精彩评论