Reputation: 653
So my understanding was that you can't use static method to access non-static variables, but I came across following code.
class Laptop {
String memory = "1GB";
}
class Workshop {
public static void main(String args[]) {
Laptop life = new Laptop();
repair(life);
System.out.println(life.memory);
}
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
}
Which compiles without errors.
So isn't
public static void repair(Laptop laptop) {
laptop.memory = "2GB";
}
accessing String memory defined in class Laptop, which is non-static instance variable?
Since the code compiles without any error, I'm assuming I'm not understanding something here. Can someone please tell me what I'm not understanding?
Upvotes: 12
Views: 42649
Reputation: 29
Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members
i.e. both static variable and static methods belongs to a class and can be called from anywhere, depending upon their access modifier.
For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere.
Similarly, a private static method can be called from a non-static method of the same class but a public static method e.g. main()
can be called from anywhere
Upvotes: 0
Reputation: 569
try this code
public static void repair() {
Laptop laptop =new Laptop();
laptop.memory="2GB";
}
Upvotes: -2
Reputation: 1800
Static methods cannot modify their value. You can get their current value by accessing them with the reference of current class.
Upvotes: 0
Reputation: 88707
A static method can access non-static methods and fields of any instance it knows of. However, it cannot access anything non-static if it doesn't know which instance to operate on.
I think you're mistaking by examples like this that don't work:
class Test {
int x;
public static doSthStatically() {
x = 0; //doesn't work!
}
}
Here the static method doesn't know which instance of Test
it should access. In contrast, if it were a non-static method it would know that x
refers to this.x
(the this
is implicit here) but this
doesn't exist in a static context.
If, however, you provide access to an instance even a static method can access x
.
Example:
class Test {
int x;
static Test globalInstance = new Test();
public static doSthStatically( Test paramInstance ) {
paramInstance.x = 0; //a specific instance to Test is passed as a parameter
globalInstance.x = 0; //globalInstance is a static reference to a specific instance of Test
Test localInstance = new Test();
localInstance.x = 0; //a specific local instance is used
}
}
Upvotes: 34
Reputation: 2200
You can access only with object reference
.
Instance variables defined at class level, have to be qualified with object name if you are using in a static context. But it does not not mean that you cannot access at all.
Upvotes: 0