Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variable in another class returns null

Tags:

java

Ok so basiclly I have three classes:

  • main class
  • Apple(two constructors)
  • Pie

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?

like image 615
JDerksen Avatar asked Dec 21 '22 10:12

JDerksen


1 Answers

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

like image 116
user000001 Avatar answered Jan 08 '23 23:01

user000001