Reputation: 1
I have a problem knowing what a part of this code works.
Here it is:
public class fia1 {
public static void main(String [] args) {
Band b0 = new Band();
b0.name = "Beastie";
b0.age = 25;
Band b1 = new Band();
b1.name = "Orchestra";
b1.age = 100;
System.out.println(b0.count);
Band b2 = new Band();
b2.name = "Polka";
b2.age = 5;
System.out.println("Names: " + b0.name + " " + b1.name + "
" + b2.name);
System.out.println(Band.count);
b1 = b2;
b1.age = 10;
b0.age = b2.age + b0.age;
System.out.println("Ages = " + b0.age + " " + b1.age + " "
+ b2.age);
}
}
class Band {
String name;
int age;
static int count = 1;
Band() {
count = count * 2;
}
}
So what this print is:
4
Names: Beastie, Orchestra, Polka
8
Ages: 35, 10, 10
I am confused as to how I get a 4 from my first count. Also I know that
static int count = 1;
is where I am misunderstanding. Is this how java counts the variables? by 1, then 2 is Beastie, 3 is Orchestra and 4 is Polka? I really don't know how this is working. Thanks for your help!
Upvotes: 0
Views: 88
Reputation: 59
the count
field in your Band
class is a static field or class variable, meaning that all object of the Band
class share it. Each time the constructor is called, count
is updated. If you want to learn more about class variables, you can check out this Java documentation
Upvotes: 1
Reputation: 954
You are using a static
variable in static int count = 1;
, which means every time you create a new Band
the variable will be doubled for all Bands
(since count = count * 2;
)
See code below with comments that explains what happens:
public static void main(String [] args)
{
Band b0 = new Band(); //Count becomes 1*2 = 2.
b0.name = "Beastie";
b0.age = 25;
Band b1 = new Band(); //Count becomes 2*2 = 4.
b1.name = "Orchestra";
b1.age = 100;
System.out.println(b0.count); //Prints 4.
Band b2 = new Band(); //Count becomes 4*2 = 8.
b2.name = "Polka";
b2.age = 5;
System.out.println("Names: " + b0.name + " " + b1.name + " " + b2.name);
System.out.println(Band.count); //Prints 8.
b1 = b2;
b1.age = 10;
b0.age = b2.age + b0.age;
System.out.println("Ages = " + b0.age + " " + b1.age + " " + b2.age);
}
Upvotes: 2
Reputation: 128
Since your variable count
is static, as it's declared as a static int count = 1;
, each new construction of the class will perform any actions on count
to all objects that have count. Anotherwords, when you call b1
, the count = count * 2;
command affects all instances of count, so the count variable in b0
is also doubled as well.
Hence, when you first construct band()
with b0
, it takes count
and sets it equal to 1 * 2 = 2. The second instance of band()
with b1
causes all instances of count to be equal to itself * 2. So, the count in b1
is equal to 1*2 = 2, and the count in b0
is equal to 2*2 = 4.
Upvotes: 0