简体   繁体   English

Java对实例和静态方法中的实例和静态变量用法的澄清?

[英]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? 我书中的问题在问:在以下定义中,实例变量和静态变量访问受到哪些限制:1.)实例方法? 2.) A static method? 2.)静态方法?

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. 编译器会以100%的可靠性告诉您所有这一切。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM