我有一個 MyClass,它的屬性型別為 MyAttribute。此類由具有 MySubAttribute 型別的屬性的 MySubClass 繼承。MySubAttribute 是 MyAttribute 的子類:
class MyClass {
MyAttribute myAttribute;
MyClass(MyAttribute myAttribute) {
this.myAttribute = myAttribute;
}
MyAttribute getMyAttribute() {
return myAttribute;
}
}
class MySubClass extends MyClass {
MySubClass(MySubAttribute mySubAttribute) {
super(mySubAttribute);
}
}
class MyAttribute {
void doSomething() {
}
}
class MySubAttribute extends MyAttribute {
@Override
void doSomething() {
super.doSomething();
}
void doSomethingElse() {
}
}
現在想象我有以下代碼:
mySubClass.getMyAttribute();
如何制作 MySubAttribute 型別的回傳值?
uj5u.com熱心網友回復:
您可以將這樣的內容添加到MySubClass:
@Override
MySubAttribute getMyAttribute() {
return new MySubAttribute();
}
uj5u.com熱心網友回復:
你應該看看Java Generics。
此外,您不再需要定義 MySubClass ,除非您想為其添加額外的方法或屬性。
class MyClass<T extends MyAttribute> {
T myAttribute;
MyClass(T myAttribute) {
this.myAttribute = myAttribute;
}
T getMyAttribute() {
return myAttribute;
}
}
class MyAttribute {
void doSomething() {
System.out.println("Doing something...");
}
}
class MySubAttribute extends MyAttribute {
void doSomethingElse() {
System.out.println("Doing something else...");
}
}
// You would instantiate `mySubClass` as follows
MyClass<MySubAttribute> mySubClass = new MyClass<>(new MySubAttribute());
mySubClass.getMyAttribute().doSomethingElse();
uj5u.com熱心網友回復:
通常的解決方案是泛型:
class MyClass<A extends MyAttribute> {
A myAttribute;
MyClass(A myAttribute) {
this.myAttribute = myAttribute;
}
A getMyAttribute() {
return myAttribute;
}
}
class MySubClass extends MyClass<MySubAttribute> {
或者,您可以讓 MySubClass 使用更窄的回傳型別覆寫 getter:
@Override
MySubAttribute getMyAttribute() {
// we know the cast succeeds because we have set a MySubAttribute in the constructor
return (MySubAttribute) myAttribute;
}
通用解決方案為實作類提供了更好的編譯時檢查,并允許呼叫者MyClass通過撰寫MyClass<MySubAttribute>. 另一方面,通用解決方案確實需要呼叫者撰寫型別引數(即使只是MyClass<?>),因此呼叫代碼會稍微冗長一些。
uj5u.com熱心網友回復:
如果我理解正確,那么您要求:
public interface HasMyAttribute {
MyAttribute getMyAttribute();
}
public class MyClass implements HasMyAttribute {
private MyAttribute myAttribute;
public MyClass(MyAttribute myAttribute) {
this.myAttribute = myAttribute;
}
@Override
public MyAttribute getMyAttribute() {
return this.myAttribute;
}
}
public class MySubClass extends MyClass implements HasMyAttribute {
private MySubAttribute mySubAttribute;
public MySubClass(MySubAttribute mySubAttribute) {
super(mySubAttribute);
this.mySubAttribute = mySubAttribute;
}
@Override
public MySubAttribute getMyAttribute() {
return mySubAttribute;
}
}
(不過,如果您不需要兩個不同的具體類,@xxMrPHDxx 的答案要好得多)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496047.html
上一篇:Linux 如何從網上下載檔案
