Vis*_*hal 2 java static non-static
我正在清除我对Java的概念.我对Java的了解远远不够,所以请耐心等待.
我试图理解静态方法和非静态方法intercalls.我知道 -
我的问题是关于非静态方法调用同一类的另一个非staic方法.在类声明中,当我们声明所有方法时,我们可以从非静态类中调用同一类的另一个非静态方法吗?
请举例说明.谢谢.
你的#3是正确的,你可以使用classname.methodname从非静态方法调用静态方法.
而你的问题似乎在于询问你是否可以从其他非静态方法中调用类中的非静态方法,这也是可能的(也是最常见的).
例如:
public class Foo {
public Foo() {
firstMethod();
Foo.staticMethod(); //this is valid
staticMethod(); //this is also valid, you don't need to declare the class name because it's already in this class. If you were calling "staticMethod" from another class, you would have to prefix it with this class name, Foo
}
public void firstMethod() {
System.out.println("This is a non-static method being called from the constructor.");
secondMethod();
}
public void secondMethod() {
System.out.println("This is another non-static method being called from a non-static method");
}
public static void staticMethod() {
System.out.println("This is the static method, staticMethod");
}
}
Run Code Online (Sandbox Code Playgroud)