Java静态关键字用法

时间:2014-04-23 23:37:42

标签: java

为什么这段代码不起作用?

HelloWorld.java:5: error: non-static method add(int,int) cannot be
referenced from a static context System.out.println(add(1,2));
  1. 我知道如果我在add方法中添加静态,它可以工作,但为什么我们必须使用静态? 如果这个代码在C中,它可以工作,对吗?
  2. 如果你没有添加静态添加方法,我可以在main中“测试”我的add方法的其他方法是什么?

    public class HelloWorld {
    
        public static void main (String []args) { 
            System.out.println(add(1,2));
        }
    
        public int add (int x, int y) {
            return x+y;
        }
    }
    

4 个答案:

答案 0 :(得分:4)

您必须将add(int, int)方法设为静态

public static int add(int x, int y) {
    return x + y;
}

或者你可以做

public static void main(String[] args) {
    HelloWorld test = new HelloWorld();
    System.out.println(test.add(1, 2));
}

之所以这样,是因为您尝试从静态方法调用它。可以在不创建对象实例的情况下使用静态方法(如第一个方案中所示)。在第二种情况下,add可以是非静态的,因为我们实际上是在创建对象的实例,因此可以访问它的非静态方法。

答案 1 :(得分:3)

是的,main方法在静态上下文中运行。如果要运行不带static关键字的方法,则需要实例化包含该方法的类。像这样:

public class HelloWorld {

    public static void main(String []args){ 

        HelloWorld helloWorld = new HelloWorld();    
        System.out.println(helloWorld.add(1,2));

    }

    public int add(int x, int y){
        return x+y;
    }
}

答案 2 :(得分:0)

static方法不需要从对象的上下文中调用;其他方法呢。如果您希望add是非静态的,请尝试以下操作:

public class HelloWorld {

    public static void main (String []args) { 
        HelloWorld h = new HelloWorld();
        System.out.println(h.add(1,2));
    }

    public int add (int x, int y) {
        return x+y;
    }
}

但是,由于HelloWorld没有任何数据成员,因此没有任何理由这样做。

答案 3 :(得分:0)

static关键字的使用是指您希望按类访问Object而不是实例。 例如,想象一下,当应用程序处于活动状态时,您希望变量相同:

class example_static{
  public final static int var= 6;
}

如果你想使用它,只需调用它的类和变量:

class example{
    public...main{
     System.out.println(String.valueOf(example_static.var));
    }
}

如果你想要一个很好的例子,只需检查Math类,很多static方法,因为做这样的事情会是多余的:

Math math = new Math(); //Eww

所以使用静态方法你可以直接调用methd并直接使用Class作为参考:

Math.methodCall(1+1);

注意

您不能从静态方法调用非静态方法,与变量相同。