靜態方法中呼叫非靜態方法
阿新 • • 發佈:2019-02-20
我們都知道,靜態static方法中不能呼叫非靜態non-static方法,準確地說是不能直接呼叫non-static方法。但是可以通過將一個物件的引用傳入static方法中,再去呼叫該物件的non-static方法。
其實這個事實的應用很經常,以至於我們不去重視:在主函式(static方法)中我們經常建立某個類的例項,再利用其飲用變數呼叫它的非靜態方法。
//StaticMethodTest.java
//A ststic method cannot call a non-static method, but we can transfer a object reference, which include a non-static metho to the static method, thus, wo can call that non-static method in a indirect way.
public class StaticMethodTest{
void NonStaticMethod(){
System.out.println("This is a non-sataic method."); }
static void StaticMethod(StaticMethodTest s){
System.out.println("This is a static method.");
s.NonStaticMethod();
} public static void main(String[] args) { StaticMethodTest sObj=new StaticMethodTest();
StaticMethod(sObj); //在主函式中可以直接呼叫靜態方法
}
}
//A ststic method cannot call a non-static method, but we can transfer a object reference, which include a non-static metho to the static method, thus, wo can call that non-static method in a indirect way.
public class StaticMethodTest{
void NonStaticMethod(){
System.out.println("This is a non-sataic method."); }
static void StaticMethod(StaticMethodTest s){
System.out.println("This is a static method.");
s.NonStaticMethod();
} public static void main(String[] args) { StaticMethodTest sObj=new StaticMethodTest();
StaticMethod(sObj); //在主函式中可以直接呼叫靜態方法
}
}