簡體   English   中英

Java接口-對象到類的類型轉換

[英]Java Interface - Object to class typecasting

我有一個看起來像的界面

公共接口KeyRetriever {

public Object getKey(Object obj);

}

我希望實現像

CustomerTypeKeyRetriever(實施類)

public String getKey(Customer customer) {
    return null;
}

我該如何實現。 當前,它引發一個編譯錯誤-“類型CustomerTypeKeyRetriever必須實現繼承的抽象方法KeyRetriever.getKey(Object)”

在接口聲明中使用泛型。

public interface KeyRetriever<T> {

public Object getKey(T obj);
}

現在在您的子類中,您可以實現它

 public class CustomerTypeKeyRetriever implements KeyRetriever<String> {
  public String getKey(String str){
        //your implementation

  }
 }

您的實現應具有類似的方法

@Override
    public Object getKey(Object obj) {
        // TODO Auto-generated method stub
        return null;
    }

我還將在所有實現方法上添加@Override批注,以便將來在API發生更改的情況下,編譯器可以捕獲任何方法更改/沖突。

如果您想要通用的界面,下面應該可以工作(這是我認為您可能想要的)

public interface KeyRetriever<T> {
    public Object getKey(T obj);
}

public class CustomerTypeKeyRetriever implements KeyRetriever<Customer> {

    @Override
    public String getKey(Customer obj) {
        // TODO Auto-generated method stub
        return null;
    }

}

由於Java支持協變返回類型,因此返回類型可以是Object的任何子類。

假設您有一個Person接口:

public interface Person {}

您的Customer和Employee類實現了:

public class Customer implements Person {/* Your class body */}
public class Employee implements Person {/* Your class body */}

然后,您可以像這樣更改界面:

public interface KeyRetriever {

public String getKey(Person person);
}

然后在客戶類中,您必須像這樣進行更改:

public String getKey(Person perosn) {
   return null;
}

希望能有所幫助。 快樂的編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM