非static方法是要与对象关联在一起的,必须创建一个对象之后才能在该对象基础之上进行方法的调用。但是static方法调用时不需要创建对象,可以直接调用。也就是说,当一个static方法被调用时,可能还没有创建任何实例对象,如果从一个static方法中发出对非static方法的调用,那个非static方法是关联到哪个对象上的呢?这个逻辑无法成立,所以,一个static方法内部无法发出对非static方法的调用。
如下是代码的具体说明:
package com.fts.test;
public class Test {
//静态方法add
public static void add(){
System.out.println("add方法的调用");
new Test().chen();//调用非静态方法
//提示错误提示Cannot make a static reference
//to the non-static method chen() from the type Test
chen();//这样调用会报错,
}
//静态方法add2
public static void add2(){
System.out.println("add2方法的调用");
}
//非静态方法chen
public void chen(){
System.out.println("chen方法的调用");
add2();//调用静态方法
}
public static void main(String[] args){
add();//方法的测试
}
}