zeesh91
zeesh91

Reputation: 153

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

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.

Upvotes: 1

Views: 110

Answers (2)

user207421
user207421

Reputation: 310884

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.

Upvotes: 3

Artem
Artem

Reputation: 7423

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.

Upvotes: 1

Related Questions