[英]how to create generic java class that extends class and implements interface?
[英]How to create an Interface for a class that extends JDialog (or in general another class)
我正在開發一個利用Swing的Java應用程序。 我有一個擴展JDialog的類,如下所示:
public class customDialog extends JDialog {
//Custom buttons listeners etc.
}
現在為它創建接口的方式(最佳實踐)是什么? 我會寫:
public interface customDialogInterface {
//Custom methods signatures
}
然后在customDialog中使用“實現customDialogInterface”,但是以這種方式,當我在代碼中使用customDialogInterface時,就無法訪問JDialog方法。 JDialog是一個類,因此我無法在我的接口中對其進行擴展。 此外,我無法使用JDialog實現的接口擴展customDialogInterface,因為其中之一是受程序包保護的。
在那些(我想是公地)案件中,正確的處理方式是什么?
更新1:我將嘗試解釋更好地重新表達我的問題。 有一種編程原理告訴“使用接口而不是具體類的程序”。 在此基礎上,如何為CustomDialog創建界面? 如果我做:
public interface CustomDialogInterface {
public void doA();
public void doB();
}
比使用CustomDialog的代碼中的我有:
CustomDialogInterface myDialog = new CustomDialog();
myDialog.doA(); //OK
myDialog.doB(); //OK
myDialog.setVisible(true); //ERROR
更新2:我決定再次更新我的問題,因為基於答案似乎還不太清楚。 它沒有很多信息,因為它不是真正的代碼,這只是一個理論問題。 另外,如果我還找到了可能的解決方案,請以另一種形式在這里再次寫:
在我的應用程序中,我需要一個包含我的信息,字段等的JDialog。如何獲取它? 定義一個類:
class MyImplementation擴展JDialog {public doA(String txt){//這是我實現的特定方法}}
現在,我要遵循良好的編程規則:“按界面編程,而不按實現編程”,因此我需要一個用於自定義對話框的界面
interface InterfaceForMyDialog {public doA(String txt); }
令人遺憾的是,類MyImplementation必須實現接口,因此我更改了上面的偽代碼,只需添加並實現
類MyImplementation擴展JDialog實現InterfaceForMyDialog {public doA(String txt){//這是我實現的特定方法}}
現在,最后我需要在外部代碼的某處(在main方法的某處)使用新對話框,如下所示:
... InterfaceForMyDialog myDialogInterface = new MyImplementation(...);
問題:如何使用“ doA(String txt)”方法完成上面的代碼以將一些文本設置到我的自定義對話框中,然后顯示對話框本身? 我認為使用這種結構是不可能的,我找到了一個使用抽象類的解決方案(見下文)。 如果我錯了或者有更好的解決方案,請在這里寫下。
正確的是,您只能擴展一個班級; 由於要擴展JDialog,因此可以實現0個或更多接口,但不能擴展另一個類。
如果您的界面有兩種方法:
public interface customDialogInterface
{
public void doA();
public int doB();
}
那你的課就可以
public class customDialog extends JDialog implements customDialogInterface
只要customDialog
具有方法doA()
和doB()
注意:按照慣例,類名和接口名都以大寫字母開頭。 如果您使用CustomDialog
和CustomDialogInterface
那么全世界的Java程序員都會更容易理解代碼。
好的,我找到了解決方案。 我沒有將CustomDialogInterface聲明為接口,而是將其聲明為擴展JDialog的抽象類。 然后,我用提供實現的類擴展此抽象類。 如果有更好的解決方案,請告訴我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.