In Liang's 9th edition Introduction to Java Programming it states, "A static method cannot access instance members of a class," (pg 312). I see why an instance member of a class would need to access a method (which might be static), but why would a method need to access an instance member? To me, "access" means "access by way of the dot operator." In other words:
Class myClass = new Class();
myClass.someStaticMethod();
makes sense, whereas:
someNonStaticMethod.myClass
or
someStaticMethod.myClass
does not. Is the someNonStaticMethod.myClass syntax allowed? I don't believe I've ever seen such formatting. If it is not allowed, why mention that static methods cannot access instance members of a class?
Please help lift my confusion.
-DI
You cannot access instance variables from static methods.
You can access instance variables from instance methods.
You should not access static variables from instance methods using
this
.You can always access static variables. You should use the class name.
Accessing an instance member means accessing a field or attribute of the instance, not the instance itself since that would not compile. A dot does not literally mean "accessing" in the exact way you think and I guess that's the source of confusion you have. The dot is used to call a method on a certain object (see this link) or to access a field of an object (or class if the field is static).
For example, assuming the class is defined as follows:
So in method
foo
, you can't referencex
because it is a member field ofMyClass
that is bound to an instance ofMyClass
.Also see Understanding Class Members to understand the difference between static members and instance members.
it is possible to access instance variables in static methods by creating objects
}
It is talking about this:
The reason a static method can't access instance variable is because static references the class not a specific instance of the class so there is no instance variable to access. Test will only exist when
new MyClass
is used now test will exist. But if I call static methodMyClass.getTest()
there is nottest
instance variable created.A static method cannot refer to a non-Static instance field of a class.
If you want to understand why: A static method can be called without having an instance of a class, thus a non-static would not exist anyway when the method is invoked.