非静态初始化器的奇怪行为

时间:2018-04-09 19:55:35

标签: java non-static

当我用int值0调用这个参数化构造函数时,这个非静态方法被调用并将其值显示为“Thal”但是当我传递一些int值时说3,这个非静态方法是添加一个元素但这次是添加的元素是构造函数类型而非非静态方法类型,我很困惑。

这是代码

public class Nimbu {
  public  static final long BLACK =0x000000;
  public  static final long GREEN =0x00FF00;
  public static String nimbuName;
  public long color = BLACK;

  public Nimbu(String nimbuName, long color) {
    this.nimbuName = nimbuName;
    this.color = color;
  }
}

public class NImbuKiBarni {
  public ArrayList<Nimbu> nimbus = new ArrayList<>();
  {        
    nimbus.add(new Nimbu("Thal", 0x00ff00));
  }    
}

public NImbuKiBarni(int nNImbu,String name,long color) {    
  for (int i = 1; i <=nNImbu ; i++) {
    nimbus.add(new Nimbu(name,color));
  }
}
}

public class Main {
  public static void main(String[] args) {
    ArrayList<Nimbu> nimbus = new NImbuKiBarni(1,"Pankhu",0x00ffff).nimbus;
    for (Nimbu n :nimbus ) {
      System.out.println("from "+n.nimbuName +" and color is "+n.color);
    }
  }
}

输出int值0

The nimbu is from Thal and color is 65280

输出int值2

 The nimbu is from Pankhu and color is 65280
 The nimbu is from Pankhu and color is 65535
 The nimbu is from Pankhu and color is 65535

1 个答案:

答案 0 :(得分:3)

问题从这里开始:

public static String nimbuName;
public long color = BLACK;

然后,在你的无格式构造函数中,你做了:

public  Nimbu(String nimbuName,long color)
{
  this.nimbuName = nimbuName;
  this.color = color;
}

虚假。使用this.nimbuNuame没有意义。您声明字段静态,因此它就像&#34;最后获胜&#34;。含义:当您创建多个 Nimbu对象时,所有这些对象都将拥有自己的颜色字段,但它们都共享 静态 nimbuName字段。

换句话说:编译器允许你写下this.nimbuName,但真正发生的是Nimbu.nimbuName - 因为没有具体&#34;按此&#34; nimbuName。所有类的实例只共享一个字符串。

这就是全部。

从这个角度来看,真正的答案是退后一步,更仔细地研究你的材料。真正的区别在于你如何宣布这两个领域。你也在混淆术语 - 你不是在调用函数,而是一个构造函数,它本质上不是静态的。

相关问题