本文介绍了非静态方法可以修改静态变量吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道非静态方法如何修改静态变量.我知道静态方法只能访问其他静态方法和静态变量.然而,另一面是真的吗?非静态方法只能访问非静态变量吗?例如:
I am wondering how a non static method can modify a static variable. I know that static methods can only access other static methods and static variables. However, is the other side true? Can non-static methods access only non-static variables? For example:
public class SampleClass {
private static int currentCount = 0;
public SampleClass() {
currentCount++;
}
public void increaseCount() {
currentCount++;
}
}
这段代码可以编译,我想知道静态访问权限方面的原因.
This code compiles and I would like to know why in terms of static access privledges.
推荐答案
我从 找到了这个Java 教程
- 实例方法可以直接访问实例变量和实例方法.
- 实例方法可以直接访问类变量和类方法.
- 类方法可以直接访问类变量和类方法.
- 类方法不能直接访问实例变量或实例方法——它们必须使用对象引用.此外,类方法不能使用 this 关键字,因为没有可供 this 引用的实例.
所以答案是肯定的,非静态方法可以修改静态变量
So the answer is yes, non-static methods CAN modify static variables
这篇关于非静态方法可以修改静态变量吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!