我写了这样的测试代码:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
但它给出了以下错误:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
我如何让我的方法识别我的类变量?
ClassLoader负责加载类文件。让我们看看当我们编写自己的类时会发生什么。
示例1:
class StaticTest {
static int a;
int b;
int c;
}
现在我们可以看到类“StaticTest”有3个字段。但实际上不存在b c成员变量。但是为什么??好的,让我看看。这里b c是实例变量。因为实例变量在对象创建时获得内存。所以这里b c还没有内存。这就是不存在b c的原因。所以只有a的存在。
对于ClassLoader,它只有一个关于a的信息。ClassLoader还不能识别b,c,因为它的对象还没有实例化。
让我们看另一个例子:
示例2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
现在如果我们尝试编译这段代码,编译器会给出CE错误。
不能从静态上下文中引用非静态方法display()。
对于ClassLoader,它看起来是这样的:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
在例2中,CE错误是因为我们从静态上下文调用非静态方法。因此ClassLoader不可能在编译时识别方法display()。因此会发生编译时错误。
对于所有初学者来说,解释静态关键词有点困难。
当你更多地使用类和对象时,你会清楚地了解它。
|*| Static:静态项可以用类名调用
如果你在代码中观察,有些函数是直接用类名调用的,比如
NamCls.NamFnc();
System.out.println();
这是因为NamFnc和println将在它们之前使用关键字static来声明。
|*|非静态:非静态项目可以用类变量调用
如果它不是静态的,你需要类的一个变量,
在类变量和后面加上点
然后调用function。
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
下面的代码简洁地解释了你
类中的静态和非静态函数:
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
类中的静态类和非静态类:
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}