Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Zippy Avatar asked Apr 30 '26 05:04

Zippy


2 Answers

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();

}
like image 123
guydog28 Avatar answered May 01 '26 19:05

guydog28


If your animate() method doesn't require any calls that are on the NewSprite object but not on the QuadBatch object, then simply change the parameter type to QuadBatch.

public void animate(QuadBatch quadBatch) {
  // animation code here
}
like image 42
NRitH Avatar answered May 01 '26 20:05

NRitH