Ok so basiclly I have three classes:
in the main class I do:
Apple apple = new Apple(String one, String two);
Then the Apple class sets them globally:
public Apple()
{
//empty constructor
}
public Apple(String one, String two)
{
this.one = one;
this.two = two;
}
Then in the Pie class I do:
Apple apple = new Apple();
Then if I try to access the variables 'one' or 'two' from the Pie class they return null. Can someone help me?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With