简体   繁体   中英

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

Then all children will have to implement bar() .

Then your if-block will be

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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