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

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

Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top