【问题标题】:Child objects and parent objects being passed into the same method子对象和父对象被传递到同一个方法中
【发布时间】:2013-09-19 20:18:19
【问题描述】:

我有一个自定义的 QuadBatch 方法,顾名思义,它可以通过一次 openGL 调用来批量绘制四边形。

我有2个对象,创建如下:

QuadBatch sprite1 = new QuadBatch();

NewSprite sprite2 = new NewSprite();

这里QuadBatch 是父类,NewSprite 是它的子类(即,它扩展了QuadBatch)。

我这样做是因为 NewSprite 需要 QuadBatch 类中的所有内容,但还需要一些额外的东西。

如果我有一个采用 NewSprite 对象的 animate 方法,如下所示:

public void animate(NewSprite newSprite){

//animation code here

}

我怎样才能使用同样的方法但传入QuadBatch 对象?我不能只传入一个QuadBatch 对象,因为该方法需要一个NewSprite 对象。

如果 animate() 方法采用的参数是 QuadBatch 对象,则同样的问题反过来适用。我怎么能传入NewSprite 对象?

【问题讨论】:

  • 查看最近的帖子 - stackoverflow.com/q/18902307/1679863
  • 如果方法有QuadBatch参数没问题,可以传NewSprite
  • 为了扩展@SotiriosDelimanolis,接受类的方法也将接受任何子类。例如,采用 java.lang.Number 的方法将接受 java.lang.Double 或 java.lang.Integer 甚至 java.math.BigDecimal。这是多态性的一部分,也是面向对象编程的关键部分。

标签: java methods arguments extends subclassing


【解决方案1】:

您只需让您的方法将父类作为参数...

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

}

【讨论】:

  • 不敢相信我没有尝试过 - 谢谢,非常有意义。
  • 我真的,真的希望 OP 不会执行您列出的第一个版本的 animate(),因为这是一种破坏面向对象的方式应该只为极端情况保留。
  • 同意,这就是为什么它基本上被写成“你可以这样做,但我希望你这样做......”
【解决方案2】:

如果您的 animate() 方法不需要在 NewSprite 对象上而不是在 QuadBatch 对象上的任何调用,则只需将参数类型更改为 QuadBatch。

public void animate(QuadBatch quadBatch) {
  // animation code here
}

【讨论】:

    【解决方案3】:

    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() 方法需要NewSprite 对象,因此您不能将QuadBatch 对象传递给它,因为QuadBatch 不是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?

    您可以将NewSprite 对象作为参数传递给animate(QuadBatch) 方法,因为NewSpriteQuadBatch 的一种类型(NewSprite 扩展QuadBatch)。

    【讨论】:

    • NewSprite 是一个 QuadBatch。这就是为什么知道什么是关系是好的。如果 NewSite 是 QuadBatch,那么为什么我不能像使用它一样使用它呢?只要知道术语,一切都会变得直观。
    【解决方案4】:

    将方法参数更改为 QuadBatch 对象

    public void animate(QuadBatch quadBatch ){
    
    //animation code here
    
    }
    

    您可以使用父类的引用创建子类的对象:

    QuadBatch quadBatch = new NewSprite();
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      相关资源
      最近更新 更多