Search code examples
javamethodsargumentsextendssubclassing

Child objects and parent objects being passed into the same method


I have a custom QuadBatch method, which as the name suggests, batches up quads to be drawn with one openGL call.

I have 2 objects, which are created as follows:

QuadBatch sprite1 = new QuadBatch();

NewSprite sprite2 = new NewSprite();

This is where QuadBatch is the parent class, and NewSprite is a subclass of it (ie, it extends QuadBatch).

I did this because NewSprite required everything in the QuadBatch class, but also some extra stuff.

If I have an animate method which takes a NewSprite object like so:

public void animate(NewSprite newSprite){

//animation code here

}

How can I use this same method but passing in a QuadBatch object? I can't just pass in a QuadBatch object as the method expects a NewSprite object.

The same question applies in reverse if the argument taken by the animate() method was a QuadBatch object. How could I pass in a NewSprite object?


Solution

  • You just have your method take the parent class as the parameter...

    public void animate(QuadBatch param) {
    
      // animation code here
    
      //if you need specific method calls you could cast the parameter here to a NewSprite
      if (param instanceof NewSprite) {
          NewSprite newSprite = (NewSprite)param;
          //do NewSprite specific stuff here
      }
    
    }
    
    //However, hopefully you have a method like doAnimate() on QuadBatch 
    //that you have overloaded in NewSprite
    //and can just call it and get object specific results
    
    public void animate(QuadBatch param) {
    
      param.doAnimate();
    
    }