Java 为什么不能通过类的引用变量调用类中定义的静态函数?

Java 为什么不能通过类的引用变量调用类中定义的静态函数?,java,reference,static,Java,Reference,Static,我有一个问题,当我试图通过类引用调用类中定义的静态函数时,为什么这段代码会给我一个错误,并且当我创建引用的对象时,可以调用静态函数 public class Example { public static void main(String args[]) { Example t; t.method();//getting error Example t1=new Example t1(); t1.method();//it runs successfully } public static

我有一个问题,当我试图通过类引用调用类中定义的静态函数时,为什么这段代码会给我一个错误,并且当我创建引用的对象时,可以调用静态函数

public class Example
{
public static void main(String args[])  
{
Example t;
t.method();//getting error
Example t1=new Example t1();
t1.method();//it runs successfully
}
public static void method()
{
System.out.println("NullPointerException");
}
}

这是可能的,但是如果你想通过引用调用任何东西,你需要先实例化它

还要记住:Java有方法,而不是函数。因此,改变:

Example t;


然后重试

t在调用
t.method()时未初始化。因此,在非实例化的t对象上会得到一个NullPointer

不应该在类的实例上调用静态方法。您应该使用类本身的名称:

public class Example
{
public static void main(String args[])  
{
Example t;       // t points to nothing (not even null, actually, its as if it doesn't exist at all)
 t.method();//getting error  // how can you call a method of example with a reference to nothing.
Example t1=new Example t1(); // t1 points to an Example object.
t1.method();//it runs successfully // works fine , but is not suggested as the method is at class level, not at instance level. use Example.method() 
}
public static void method()
{
System.out.println("NullPointerException");
}
}
Example.method()

另外,当您声明一个变量并没有初始化它时,它将不会被初始化(局部变量),当您尝试对它调用方法时,您将得到错误

他不能只执行示例。方法()?因为它是静态的,是的,他可以,是的,他应该这样做。但问题是:为什么我不能通过一个实例来实现它。你应该用“使用实例访问静态方法是不好的”:)t未初始化,它是空的。要比“给出错误”更具体。指定编译时间或运行时,错误消息。@J.Rush
t
不为空,未初始化。与实例变量不同,局部变量必须显式初始化。@ABFORCE您实际尝试过吗?此代码给出了一个编译器错误,因此无法运行。看看那些没有经验的当地人。@ggovan你说得对,非常感谢你!不能对类的实例调用静态方法。你可以,但你不应该。@ggovan是的,你是对的,我会编辑它。因此,当你声明一个变量并没有初始化它时,它将被初始化为null。仅在实例变量上,而不是局部变量上。因此编译器抱怨提问者得到了。@ggovan我的意思是继承自
Object
@ggovan的非原语类型。我在谷歌上搜索并阅读了一些文章,是的,你是对的,它不是空的
t
,因为它是一个静态方法调用,所以实际上没有使用它。在这里您不会得到NPE。当第一次调用
t.method()
时,
t
不为空!它还没有草签。如果
t
为空,则代码将编译,并且该方法将被正确调用,因为它是一个静态方法调用。@ggovan-谢谢。。嗯。。我真傻,竟然用“null”…)
Example.method()