【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关键字)。

【说明】

本文可能未必适用所有情形,本人尚属初学者,如有错误或疑问请评论提出,由衷感谢!

  • 19
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值