You are creating two different objects. If you want all Apple objects to have the same parameter, declare them as static
. Otherwise the behavior is correct.
More specifically, the apple
that you create in the main class, will have the desired values in it's parameters. The second apple
, that is created in the Pie
class (and it is a different object i.e. another instance of the Apple class), since it is constructed without any parameters, the default constructor (i.e. public Apple()
) will be called, and the values will return null.
To see the difference between a static
and a non-static
variable do the following:
class Apple {
int var;
}
Apple apple1 = new Apple();
apple1.var = 10;
Apple apple2 = new Apple();
apple2.var = 5;
System.out.println(apple1.var+"\t"+apple2.var);
Prints:
10 5
But if it is static
you will get
class Apple {
static int var;
}
Apple apple1 = new Apple();
apple1.var = 10;
Apple apple2 = new Apple();
apple2.var = 5;
System.out.println(apple1.var+"\t"+apple2.var);
The output will be:
5 5
For more info on when to use static or not, have a look at:
Java: when to use static methods