Java clarification on instance and static variable usage from within instance and static methods?

StackOverflow https://stackoverflow.com/questions/22289979

문제

Question in my book is asking: What restrictions are placed on instance variable and static variable access from within the definition of: 1.) An instance method? 2.) A static method?

Is my response to this concept correct?

-An instance method cannot directly access the instance variable while a static variable can be directly accessed since one copy is used throughout the class. (Each object will share this static variable as well as the static methods in the class. An instance variable is only available to each object and each object has its own copy of this instance variable.) A static method cannot access instance members of the class. A static method can however access members of the static variable.

도움이 되었습니까?

해결책

An instance method cannot directly access the instance variable

Wrong.

while a static variable can be directly accessed since one copy is used throughout the class.

Correct.

(Each object will share this static variable as well as the static methods in the class.

Correct.

An instance variable is only available to each object and each object has its own copy of this instance variable.)

Correct.

A static method cannot access instance members of the class.

Correct.

A static method can however access members of the static variable.

Correct, if it has members, and they are accessible.

The compiler would have told you all this with 100% reliablity.

다른 팁

That's right, simply put:

Instance methods can access instance and static variables of the same class (if other access modifiers permit so);

Static methods can only access static variables of the same class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top