I'm writing some JAVA assignment I got in school for a few days now, and I ran into something quite weird (well, at least for me it is...).
Since the question has nothing to do with my project in particular, I wrote some code that presents the behaviour I wanted to ask about, so please ignore any problems you might encounter in the following code, that don't relate to this specific issue.
Consider the following class:
package test;
import java.util.ArrayList;
import java.util.List;
public class Car {
List<Doors> doors;
int numOfDoors;
public Car(int numOfDoors) {
this.numOfDoors=numOfDoors;
}
public void prepare() {
run(doors);
}
public void run(List<Doors> listOfDoors) {
listOfDoors=new ArrayList<Doors>(numOfDoors);
}
public List<Doors> getDoors() {
return doors;
}
}
And this:
package test;
import java.util.List;
public class TestDrive {
public static void main(String[] args) {
Car car=new Car(5);
car.prepare();
List<Doors> listOfDoors=car.getDoors();
if (listOfDoors==null) {
System.out.println("This is not the desired behaviour.");
}
else {
System.out.println("This is the desired behaviour.");
}
}
}
I agree, it's kinda stupid and has no point, but again - I wrote it only to satisfy my curiosity.
Now, as you might have guessed, the output is "This is not the desired behaviour.", meaning, the field "doors" holds a null pointer, even though it was assigned with a new object in "run()" method. so my question is why? why is it null?
I mean, I know that creating a local variable - may it be a primitive, an object or a reference to an object - will result in loosing it right when we leave the method's scope, but that is not exactly the case here, since there IS a live reference to that newly created object (doors), then why would JAVA destroy it?