简体   繁体   中英

add a static variable and a non static variable together in java

Can we add a static variable and a non static variable together in java? For example,

class Evolve{
    static int i = 1;
    static int j = 2;
    int x = 3;
    static int y = 6;

    public static void main(String args[]){
        System.out.println(i + j);
        System.out.println(x + i);
        System.out.println(i + y);
        System.out.println(x + j);
    }
}

Thanks

Not until you initialize an instance of Evolve and refer to it as

this.i

or like this

Evolve evolve = new Evolve();
System.out.println(evolve.i + Evolve.j);

不, 非静态 (或instance )变量xmain方法的静态上下文中不可访问。

您需要将非静态对象置于实例中,然后可以使用Evolve.i + this.x添加它们

There is nothing to do with static/non-static about whether you can add it or not.

It is simply how you should access static and non-static (instance) variable.

Since x is an instance variable, you need an instance of the Evolve object...

public static void main(String args[]){
  Evolve ev = new Evolve();
  System.out.println(Evolve.i + Evolve.j);
  System.out.println(ev.x + Evolve.i);
  System.out.println(Evolve.i + Evolve.y);
  System.out.println(ev.x + Evolve.j);
}

您可以将静态变量加在一起,但要添加带有静态变量的非静态变量,则必须使用this。(“ non-static variable”),但静态方法除外。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM