java - Java 中的静态方法调用是如何工作的?

When calling out the function testFunc(), I am not using the syntax Apples.testFunc(). Yet the code runs successfully. How so?


class Apples {

       public static void main(String args[] ) {
           testFunc();
       }   

       public static void testFunc() {
           System.out.println("Hello world!");
       }
    }

最佳答案

因为,静态方法在同一个类中。因此,您无需指定类名。

如果在不同的类中,则需要指定类名。

记住:非静态方法可以访问静态和非静态成员,而静态方法只能访问静态成员。

例如 :

调用不同类中存在的静态方法,您需要这样做:

import com.example.Test;

public class Apples {

   public static void main(String args[]) {
      Test.testFunc();
   }   
}
package com.example;

public class Test {

   public static void testFunc() {
      System.out.println("Hello world!");
   }

}

https://stackoverflow.com/questions/62195858/

相关文章:

timeout - Marklogic:XDMP-EXTIME 错误(超出时间限制)

vba - UDT 能否以任何方式用作方法参数?

object-detection - 使用 >450K 个实例训练 Dlib 对象检测

ada - 如何明确指定字 rune 字

c - 我无法理解打印第一个八个数组元素的数组的输出

electron - 如何将在 Electron 上开发的桌面应用程序打包成.exe?

d3.js - 使用 d3 v4.0 重新创建集群力布局

r - 如何创建一个因子但保留基础值,而不仅仅是整数代码?

java - 这个While 循环可以简化吗?

prolog - Prolog数据库的Web访问