非静态初始值设定项奇怪的行为

non static initializers strange behaviour

当我用 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

问题从这里开始:

public static String nimbuName;
public long color = BLACK;

然后,在你未格式化的构造函数中你做:

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

这是伪造的。使用 this.nimbuNuame 没有意义。您声明 fieldstatic,因此它类似于 "last wins"。意思是:当你创建多个 Nimbu对象时,所有这些对象都会有自己的色域,但它们都是共享的 static nimbuName 字段。

换句话说:编译器允许你写下this.nimbuName,但真正发生的是你写下Nimbu.nimbuName——因为有没有具体 "per this" nimbuName。 class.

的所有实例仅共享一个字符串

仅此而已。

从这个角度来看,真正的答案是退后一步,更仔细地研究您的 material。真正的区别在于您声明这两个字段的方式。您还混淆了术语 - 您不是在调用函数,而是在本质上不是静态的 constructor