Note that there are some explanatory texts on larger screens.

plurals
  1. POLocal object creation in JAVA
    text
    copied!<p>I'm new to java, so please bare with me... </p> <p>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...).<br> 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.<br> Consider the following class: </p> <pre><code>package test; import java.util.ArrayList; import java.util.List; public class Car { List&lt;Doors&gt; doors; int numOfDoors; public Car(int numOfDoors) { this.numOfDoors=numOfDoors; } public void prepare() { run(doors); } public void run(List&lt;Doors&gt; listOfDoors) { listOfDoors=new ArrayList&lt;Doors&gt;(numOfDoors); } public List&lt;Doors&gt; getDoors() { return doors; } } </code></pre> <p>And this:</p> <pre><code>package test; import java.util.List; public class TestDrive { public static void main(String[] args) { Car car=new Car(5); car.prepare(); List&lt;Doors&gt; listOfDoors=car.getDoors(); if (listOfDoors==null) { System.out.println("This is not the desired behaviour."); } else { System.out.println("This is the desired behaviour."); } } } </code></pre> <p>I agree, it's kinda stupid and has no point, but again - I wrote it only to satisfy my curiosity. </p> <p>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?<br> 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 <strong>live</strong> reference to that newly created object (doors), then why would JAVA destroy it?<br> Thanks for anyone who made it through and read the whole post.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload