java中static的使用
我想知道是否可以在非静态方法中使用静态变量?
我还
可以在静态方法中使用非静态变量吗?
谢谢
I want to know if it is possible to use a static variable inside a non static methode ?
also
can I use a non static variable inside a static methode ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
静态变量可以从任何你喜欢的地方访问。
非静态变量只能从非静态方法或特定对象(类的实例)访问。
其原因可能非常复杂,但简而言之:
每当从该类实例化对象时,类中的任何非静态内容都会被复制。任何静态内容对于类的所有实例都是通用的(并且不会为新对象重复),这意味着它不受单个对象状态变化的影响。
现在显然,在创建类的实例之前,任何非静态的东西都不能存在——它们没有对象可以归属。由于静态成员不需要类的实例存在,因此它们访问需要对象实例(非静态)的成员是不安全的。
A static variable can be accessed from anywhere you like.
A non static variable can only be accessed from a non static method or from a specific object (instance of a class).
The reason for this can get quite complicated, but in brief:
Anything that is non static in your class is duplicated whenever an object is instantiated from that class. Anything static is common to all instances of the class (and not duplicated for new objects), meaning it is unaffected by changes in the state of individual objects.
Now obviously until an instance of the class has been created, anything non static cant exist - there's no object for them to belong to. Since static members dont require an instance of a class to exist, it wouldnt be safe for them to access members that do require an instance of an object (non static).
两者都是可能的,但要访问实例(非静态)变量,您需要一个实例。
这可以在非静态上下文中隐式给出,例如在实例方法中,并且必须在静态上下文中显式提供。
Both are possible, but to access an instance (non-static) variable you need an instance.
This can be given implicitly in a non-static context like in an instance method, and must be provided explicitly in a static context.
是的。
不。
Yes.
No.
考虑一下在静态上下文中使用非静态变量意味着什么。静态方法不在任何实例上执行 - 因此,对类上定义的成员字段进行操作意味着什么?该字段属于哪个实例?没有任何!
相反的情况,即在非静态上下文中使用静态变量是完全有意义的。您在一个实例上,并且想要读取为给定类的所有实例定义的一些静态引用。
Think about what it means to use a non-static variable in a static context. A static method is not executing on any instance - therefore, what would it mean to operate on a member field defined on the class? What instance does that field belong to? None!
The opposite scenario, namely, using a static variable in a non-static context makes perfect sense. You're on an instance, and you want to read some static reference that is defined for all instances of a given class.
是的。
仅当您在该静态方法中有可用的类实例时。
Yes.
Only if you have an instance of the class available inside that static method.