Author Topic: this == null  (Read 2675 times)

Offline slenkar

  • byte
  • *
  • Posts: 20
    • View Profile
this == null
« on: May 31, 2009, 11:43:33 pm »
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?

Offline paulscode

  • double
  • *****
  • Posts: 863
    • View Profile
    • PaulsCode.Com
Re: this == null
« Reply #1 on: June 01, 2009, 01:01:17 am »
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.

Offline slenkar

  • byte
  • *
  • Posts: 20
    • View Profile
Re: this == null
« Reply #2 on: June 01, 2009, 01:09:34 am »
ah ok thanks