当前位置: 移动技术网 > IT编程>开发语言>Java > 【踩坑】报错 non-static method xxx() cannot be referenced from a static context

【踩坑】报错 non-static method xxx() cannot be referenced from a static context

2019年03月26日  | 移动技术网IT编程  | 我要评论

今天测试代码时遇到

  • error:(6, 55) java: non-static method saygoodbye() cannot be referenced from a static context

的报错,代码如下:

public class helloworld {
    public static void main(string[] args) {
        system.out.println("greeting: " + goodbyeworld.saygoodbye());
    }
}
class goodbyeworld {
    public string saygoodbye() {
        return "goodbye";
    }
}

原因:

不能直接调用类变量和类方法。

解决方法一:

将方法改成类方法,如下:

public class helloworld {
    public static void main(string[] args) {
        system.out.println("greeting: " + goodbyeworld.saygoodbye());
    }
}
class goodbyeworld {
    public string static saygoodbye() {
        return "goodbye";
    }
}

解决方法二:

生成实例,调用实例中的非静态方法,如下:

public class helloworld {
    public static void main(string[] args) {
        goodbyeworld greeting = new goodbyeworld();
        system.out.println("greeting: " + greeting.saygoodbye());
    }
}
class goodbyeworld {
    public string saygoodbye() {
        return "goodbye";
    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网