簡體   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