I’m writing a simple web browser in Java. I have a class, WebBrowserPane, which extends JEditorPane and sets it up for better displaying web pages (disables editing, adds a HyperlinkListener etc.). I then have a class, WebBrowserFrame, which extends JFrame and places some buttons and an address bar at the top and a WebBrowserPane below. Rather than it only being able to place a WebBrowserPane below, though, I would like it to take anything which extends JEditorPane and has the relevant methods.
I wrote an abstract class, AbstractBrowser to achieve this:
import javax.swing.JEditorPane;
public abstract class AbstractBrowser extends JEditorPane {
public void back(){}
public void forward(){}
public void refresh(){}
}
WebBrowserPane then extends AbstractBrowser:
public class WebBrowserPane extends AbstractBrowser {
WebBrowserPane(){
setEditable(false);
//etc
}
public void back(){
//blah
}
}
WebBrowserFrame then takes any AbstractBrowser as a parameter:
public class WebBrowserFrame extends JFrame{
WebBrowserFrame(AbstractBrowser a){
add(a);
}
}
Obviously this doesn’t ensure that the abstract classes methods are ever overridden so I realise its not a very good solution. Is there a way to accomplish this using an interface instead?
The problem is that an interface can’t extend JEditorPane. But you can declare abstract methods in an abstrac class, and the compiler would force any child class to override them: