Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't I define a static method in a Java interface?
    text
    copied!<p>Here's the example:</p> <pre><code>public interface IXMLizable&lt;T&gt; { static T newInstanceFromXML(Element e); Element toXMLElement(); } </code></pre> <p>Of course this won't work. But why not?</p> <p>One of the possible issues would be, what happens when you call:</p> <pre><code>IXMLizable.newInstanceFromXML(e); </code></pre> <p>In this case, I think it should just call an empty method (i.e. {}). All subclasses would be forced to implement the static method, so they'd all be fine when calling the static method. So why isn't this possible?</p> <p><strong>EDIT:</strong> I guess I'm looking for answer that's deeper than "because that's the way Java is". </p> <p>Is there a particular technological reason why static methods can't be overwritten? That is, why did the designers of Java decide to make instance methods overrideable but not static methods?</p> <p><strong>EDIT:</strong> The problem with my design is I'm trying to use interfaces to enforce a coding convention.</p> <p>That is, the goal of the interface is twofold:</p> <ol> <li><p>I want the IXMLizable interface to allow me to convert classes that implement it to XML elements (using polymorphism, works fine).</p></li> <li><p>If someone wants to make a new instance of a class that implements the IXMLizable interface, they will always know that there will be a newInstanceFromXML(Element e) static constructor.</p></li> </ol> <p>Is there any other way to ensure this, other than just putting a comment in the interface?</p> <p><strong>EDIT:</strong> <em>As of Java 8, static methods are now allowed in interfaces.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload