Question

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?

Was it helpful?

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

}

OTHER TIPS

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
}

1.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.

animate() method expects NewSprite object so you can't pass the QuadBatch object to it,since QuadBatch is not of type NewSprite.

2.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?

You can pass NewSprite object as argument to animate(QuadBatch) method since NewSprite is a type of QuadBatch(NewSprite extends QuadBatch).

Change the method argument to QuadBatch object

public void animate(QuadBatch quadBatch ){

//animation code here

}

You can create an object of subclass using reference of parent class :

QuadBatch quadBatch = new NewSprite();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top