When calling out the function
testFunc()
, I am not using the syntaxApples.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/