1. 程式人生 > >【Android】AS報錯解決方法:Non-static method '*' cannot be referenced from a static context

【Android】AS報錯解決方法:Non-static method '*' cannot be referenced from a static context

轉載請註明出處,原文連結:https://blog.csdn.net/u013642500/article/details/80156306

【錯誤】

Non-static method '*' cannot be referenced from a static context

【翻譯】

在靜態上下文中不能引用非靜態方法'*'

【造成原因】

直接呼叫了其他包內的非靜態方法。

【舉例】

包 com.test.package1 中有類 TestMethod,該類中有非靜態方法 test()。

package com.test.Package1;

public class TestMethod {
    public void test(){
        // 方法內容
    }
}

包 com.test.package2 中有類 Test,該類中某方法內引用包 com.test.package1 中 TestMethod 類的 test()方法。

package com.test.Package2;

import com.test.TestMethod;

public class Test {
    public void testUseMethod(){
        TestMethod.test();
        // 此處報錯:Non-static method 'test()' cannot be referenced from a static context
    }
}

【解決方法1】

將包 com.test.package1 中 TestMethod 類的非靜態方法 test() 改為靜態方法。

package com.ssc.mt.magictower.Package1;

public class TestMethod {
    public static void test(){    // 給test()方法新增關鍵字static
        // 方法內容
    }
}

【解決方法2】

引用包 com.test.package1 中 TestMethod 類的 test()方法時,先例項化一個 TestMethod 類的物件,再用物件引用方法。

package com.ssc.mt.magictower.Package2;

import com.ssc.mt.magictower.Package1.TestMethod;

public class Test {
    public void testUseMethod(){
        TestMethod testMethod = new TestMethod();
        testMethod.test();
        // 先例項化物件,再通過物件引用方法
    }
}

【相關報錯】

錯誤:Static member '*' accessed via instance reference

造成原因:例項化物件後,通過物件引用了靜態方法。

解決方法1:直接通過類名引用方法。

解決方法2:將靜態方法改為非靜態方法(刪去static關鍵字)。

【說明】

本文可能未必適用所有情形,本人尚屬初學者,如有錯誤或疑問請評論提出,由衷感謝!