When I call this parameterized constructor with int value 0 this non static method is being called and shows its value as "Thal" but when I pass some int value say 3, this non static method is adding one element but this time the element is added is constructor type not non static method type, I'm confused.
Here is the code
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);
}
}
}
Output with int value 0
The nimbu is from Thal and color is 65280
Output with int value 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
Problems start here:
public static String nimbuName;
public long color = BLACK;
And then, in your unformatted constructor you do:
public Nimbu(String nimbuName,long color)
{
this.nimbuName = nimbuName;
this.color = color;
}
Which is bogus. There is no point in using this.nimbuNuame
. You declared that field to be static, therefore it is like "last wins". Meaning: when you create multiple Nimbu objects, then all these objects will have their own color field, but they are all sharing the static nimbuName field.
In other words: the compiler allows you to write down this.nimbuName
, but what really happens is that you do Nimbu.nimbuName
- because there is no specific "per this" nimbuName. There is only one string shared by all instances of the class.
That is all there is to this.
From that point of view, the real answer for you is to step back and study your material much more carefully. The real difference is how you declared those two fields. You are also mixing up terminology - you are not calling functions but a constructor which is by nature not static.