Reputation: 11
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. 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.
Upvotes: 1
Views: 199
Reputation: 794
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();
}
Upvotes: 0
Reputation: 533880
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();
;
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. i.e. you only need it's class.
result = rnd.nextBoolean() ? a.getClass().newInstance() : b.getClass().newInstance();
Upvotes: 2
Reputation: 9491
put public var abstract bar() {}
in the abstract class.
Then all children will have to implement bar()
.
Then your if-block will be
if(rnd.nextInt(2) == 0) {
return a;
} else {
return b;
}
Upvotes: 3