以下所说的方法和类都是public

1.使用methodName()的情况

  • 在同一个类中,(1)非static方法调用非static方法(这种情况也可用this.methodName())
  • 在同一个类中,非static方法调用static方法(这种情况也可用ClassName.methodName())
  • 在同一个类中,(2)static方法调用static方法(这种情况也可用ClassName.methodName())
  • 递归调用(这种情况可用算在(1)或(2)中)

2.使用instanceName.methodName()的情况

  • 在同一个类中,static方法调用非static方法
  • 在不同的类之间,一个类中的方法调用另一个类中的非static方法

3.使用ClassName.methodName()的情况

  • 在不同的类之间,一个类中的方法调用另一个类中的static方法

4. 使用super.methodName()的情况

  • 子类方法调用父类方法

用法总结:

1.一个方法a调用非static方法,一般用instanceName.methodName(),如果是在同一个类中,且a为非static方法,要用this.methodName(),或者省略this(this指代当前对象);如果a是static方法,不可用this,因为static方法在定义类的时候就载入到内存中,而此时this指代的当前对象并没有被创建(不存在),所以static方法里不能用this。

2.一个方法b调用static方法,通用ClassName.methodName(),如果是在同一个类中,要省略ClassName

3.省略(即直接用methodName()),只发生在同一个类中。

知其然,更知其所以然:

static方法会随着类的加载而被加载到内存中,但是非static方法从属于类的具体实例,只有实例化(用类创建对象的过程)后,对象的内存中才有这个方法的代码段,static方法载入内存中的时机先于非static方法。

所以,只有在实例化后,才可以调用非static方法;而调用static方法,不要实例化。