this == null

Started by slenkar, May 31, 2009, 11:43:33 PM

Previous topic - Next topic

slenkar

here is my bullet class with constructor:

public class Bullet{
   
   public static ArrayList list ;
   public Object3D obj;
   
   public Bullet(Object3D parent)
   {
   
      
      if (list==null)
      {
         ArrayList<Bullet> list = new ArrayList<Bullet>();
      }
      
      
      this.obj=HelloWorldAWTGL.bullet.cloneObject();
       this.obj.setBillboarding(true);
       obj.setCollisionMode(Object3D.COLLISION_CHECK_SELF);
       HelloWorldAWTGL.world.addObject(this.obj);
       Matrix pos=parent.getTranslationMatrix().cloneMatrix();
       Matrix rot=parent.getRotationMatrix().cloneMatrix();
       this.obj.setTranslationMatrix(pos);
       this.obj.setRotationMatrix(rot);
       list.add(this);
   }

when i try to add 'this' to the list it says this==null in the debugger, but the other operations on 'this' all work fine.

can anyone help?

paulscode

That error is a safeguard to prevent incompletely constructed objects from being visible externally.  The other places you used "this" do not have a problem because there is no problem with accessing the internal members of "this" from inside the constructor (it is all internal).  But you cannot publish an external reference to "this" (placing it into a public static list in your example) before it is fully constructed.  It would be clearly undesirable, for example, if another thread was able to access the object before it was completely instantiated.  After all, how could you tell the properly constructed objects from the incomplete ones?  By publishing a reference to "this" from inside a constructor you would be inviting unpredictable results.

I would recommend creating some type of external "bullet manager" class that places the bullet into the list, etc. after it is finished being instantiated.

slenkar