为什么非静态类方法应该与实例一起使用?

huangapple 未分类评论53阅读模式
英文:

Why should a non static class method be used with instance?

问题

我现在正在学习关于静态和方法的知识,我对这些内容有一些疑问。

所以,我首先尝试了这个代码:

class Calculator{
    int addNumbers(int a, int b){
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Calculator.addNumbers(1, 23));
    }
}

但我得到了以下错误信息:

Error:(11, 38) java: non-static method addNumbers(int,int) cannot be referenced from a static context

于是,我查找了一下,有人说我应该像下面这样在一个实例中调用方法,然后这个方法就能正常工作了:

class Calculator{
    int addNumbers(int a, int b){
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.addNumbers(1, 23));
    }
}

我想知道为什么我不能在不使用实例的情况下使用非静态方法。
为什么类方法必须使用实例来调用?这只是规定吗?
到目前为止,我只是觉得由于 main() 方法是静态的,其他类中的所有内容都应该是静态的,才能在 main 方法中使用。

英文:

I'm studying about static and methods now.. and I have some questions about these..

So, I tried this one first

class Calculator{
    int addNumbers(int a,int b){
        return a+b;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Calculator.addNumbers(1,23));
    }
}

And I got this error message

Error:(11, 38) java: non-static method addNumbers(int,int) cannot be referenced from a static context

So, I searched and people said I should call the method in an instance like below and it worked..

class Calculator{
    int addNumbers(int a,int b){
        return a+b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.addNumbers(1,23));
    }
}

I'm wondering why I can't use the non static method without using instance..
Why do class methods have to be used with instance? Is it just the rule??
So far I just feel like since main() method is static everything in other class should be static to be used in main method..

huangapple
  • 本文由 发表于 2020年6月29日 05:12:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/62628282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定