[英]Two different object types as argument, returning objects of ones type
I've such problem - have one abstract class, and many classes that inherits from that class. 我有这样的问题-有一个抽象类,以及从该类继承的许多类。 I have function which gets as arguments objects of that non-abstract classes.
我有功能,该参数作为非抽象类的对象。 It has to return object of non-abstract class, but I know which exectly in runtime.
它必须返回非抽象类的对象,但是我知道在运行时哪个对象正确。 Any ideas?
有任何想法吗?
Here sample code, how its looks like: 下面是示例代码,其外观如下:
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();
}
In both classes method bar() do the same thing. 在这两个类中,方法bar()都做同样的事情。 And now to do such thing:
现在要做这样的事情:
/* 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 */
}
Thanks for help. 感谢帮助。
put public var abstract bar() {}
in the abstract class. 将
public var abstract bar() {}
放在抽象类中。
Then all children will have to implement bar()
. 然后,所有子代都必须实现
bar()
。
Then your if-block will be 那么你的if-block将是
if(rnd.nextInt(2) == 0) {
return a;
} else {
return b;
}
You appear to be making things complicated for yourself. 您似乎正在使自己变得复杂。
/*
btw. my second question is, how to do such thing:
a.bar(); ?
*/
You add bar()
to Shape
and call a.bar();
您将
bar()
添加到Shape
并调用a.bar();
; ;
if(rnd.nextInt(2) == 0) {
/* result is type of a */
} else {
/* result is type of b */
This is fairly obtuse coding. 这是相当钝的编码。 It's not clear why you would pass an object if you don't intend to use it.
目前尚不清楚,如果您不打算使用对象,为什么要传递它。 ie you only need it's class.
即,您只需要它的类。
result = rnd.nextBoolean() ? a.getClass().newInstance() : b.getClass().newInstance();
Or you can do a class cast. 或者,您可以进行课堂演员表转换。
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.