![](/img/trans.png)
[英]How do I enforce that a class implementing an interface or a subclass extending an abstract class must provide a default constructor?
[英]How do I convert an abstract class into an interface?
我有一個使用arraylists的java程序 - 這些arraylists存儲'變量',其中'變量'是一個抽象類。
現在,為了節省內存,我想使用一個名為HugeCollections-VanillaJava的java庫 - 但是這個庫需要定義一個接口。
如何將抽象類轉換為接口? 為了正確執行轉換,我必須遵循哪些規則/限制?
最后,我是否可以使用我的抽象類進行最少的代碼更改,以便需要接口的庫也能正常工作? 理想情況下,我不想改變抽象類......這可能嗎?
如何將抽象類轉換為接口?
制作抽象類源文件的副本。
在初始聲明中將“class”更改為“interface”。
更改名稱(可選,取決於您正在做什么)。
刪除該類實現的任何方法的主體。
從其他單詞中刪除“abstract”一詞。
刪除所有私有和受保護的成員。
刪除所有構造函數。
從公共成員中刪除關鍵字“public”。
如果您刪除了任何代碼(已實現的方法,私有或受保護的東西),請讓您的原始抽象類實現您的界面並將其保留在那里。
(不完整)示例:
Foo
作為抽象類:
public abstact class Foo
{
private int bar;
public static final int SOME_CONSTANT = 42;
public Foo(b) {
this.bar = b;
}
public abstract void doSomething(String s);
protected int doSomethingElse() {
return this.bar * 2;
}
}
Foo
作為界面:
public interface Foo
{
int SOME_CONSTANT = 42;
void doSomething(String s);
}
在我的情況下,因為我確實有舊Foo
做的一些東西,我可能有AbstractFoo
或其他東西:
public abstact class AbstractFoo implements Foo
{
private int bar;
public Foo(b) {
this.bar = b;
}
public abstract void doSomething(String s);
protected int doSomethingElse() {
return this.bar * 2;
}
}
...如果需要,一個實現可以使用它作為一個起點(盡管那里有private
bar
,它沒有多大意義)。
Pattern Adapter可能對您有所幫助。
想象一下,你必須使用SomeClass作為TargetInterface
public abstract class SomeClass {
// some code here
public abstract void someMethod();
}
public interface TargetInterface {
public void someMethodBlaBla();
}
他們有不同的方法簽名 - someMethod()和someMethodBlaBla() 。
所以你可能會創建這樣的適配器類:
public class Adapter implements TargetInterface {
private SomeClass adaptee;
public Adapter( SomeClass adaptee ) {
this.adaptee = adaptee;
}
public void someMethodBlaBla() {
this.adaptee.someMethod();
}
//delegate all calls to adaptee
}
在代碼中的某個地方你可以使用 - 適配器和抽象類的實例,而不會干擾當前代碼:
SomeClass abstractClassInstance = ... //get instance of your abstract class
TargetInterface targetInterfaceInstance = new Adapter( abstractClassInstance );
如果抽象類沒有定義任何具體方法,您甚至可以使用正則表達式。 從:
public abstract class Abstract {
public abstract void method();
//...
}
至:
public interface Interface {
void method();
//...
}
public abstract
修飾符是接口隱式的。 如果abstract
類確實定義了一些方法(並非所有方法都是abstract
)或者有一些字段,則無法完成(至少很容易)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.