繁体   English   中英

两种不同的对象类型作为参数,返回一个类型的对象

[英]Two different object types as argument, returning objects of ones type

我有这样的问题-有一个抽象类,以及从该类继承的许多类。 我有功能,该参数作为非抽象类的对象。 它必须返回非抽象类的对象,但是我知道在运行时哪个对象正确。 有任何想法吗?

下面是示例代码,其外观如下:

public abstract class Shape {
    int x, y;
    void foo();
}

public class Circle extends Shape {
    int r;
    void bar();
}

public class Square extends Shape {
    int a;
    void bar();
}

在这两个类中,方法bar()都做同样的事情。 现在要做这样的事情:

/* in some other class */
public static Shape iHateWinter(Shape a, Shape b) {
    Random rnd = new Random();
    Shape result;

    /* 
     btw. my second question is, how to do such thing: 
     a.bar(); ?
    */

    if(rnd.nextInt(2) == 0) {
       /* result is type of a */
    } else {
       /* result is type of b */
}

感谢帮助。

public var abstract bar() {}放在抽象类中。

然后,所有子代都必须实现bar()

那么你的if-block将是

if(rnd.nextInt(2) == 0) {
      return a;
    } else {
      return b;
    }

您似乎正在使自己变得复杂。

/* 
 btw. my second question is, how to do such thing: 
 a.bar(); ?
*/

您将bar()添加到Shape并调用a.bar(); ;

 if(rnd.nextInt(2) == 0) {
    /* result is type of a */
 } else {
    /* result is type of b */

这是相当钝的编码。 目前尚不清楚,如果您不打算使用对象,为什么要传递它。 即,您只需要它的类。

 result = rnd.nextBoolean() ? a.getClass().newInstance() : b.getClass().newInstance();

或者,您可以进行课堂演员表转换。

if(a instanceof Circle)
{ Circle c = (Circle) a;
  c.bar();
}

if(a instanceof Square)
{ Square s = (Square) a;
  s.bar();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM