Static methods in interfaces

Java cognoscenti,
Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

No, it's not the same. You are not "defering the
implementation of a static method" because static
methods are never polymorphic.
Static methods cannot be abstract for this reason, and
only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
A short summary of what I've learnt so far:
- interfaces cannot contain static methods
- abstract classes cannot contain abstract static methods
- static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
/* output
SuperClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
SuperClass.someMethod()
SubClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
public class Test {
  public final static void main(String[] args) {
      // output: SuperClass.someMethod()
      new SuperClass().someMethod();
      // output: SubClass.someMethod()
      new SubClass().someMethod();
      // output: 2x SuperClass.someMethod()
      SuperClass someClass1 = new SubClass();
      someClass1.someMethod();
      showSuper(someClass1);
      // output: 2x SubClass.someMethod()
      SubClass someClass2 = new SubClass();
      someClass2.someMethod();
      showSub(someClass2);
      showSuper(someClass2); // SuperClass.someMethod()
  public final static void showSuper(SuperClass c) {
        c.someMethod();
  public final static void showSub(SubClass c) {
        c.someMethod();
class SuperClass {
  public static void someMethod() {
    System.out.println("SuperClass.someMethod()");
class SubClass extends SuperClass {
  public static void someMethod() {
    System.out.println("SubClass.someMethod()");

Similar Messages

  • Static methods in interface (Yes, once again!)

    I know there has been many questions about why static methods in interfaces are not allowed. I know it is forbidden by the JLS. But does anyone know the exact reason for this? Is it just a design issue or are there technical difficulties with allowing it?
    I can't think of any reason that it should be impossible to allow static methods in interfaces. I don't even think it would be very difficult to do. More importantly, it could probably be done without breaking existing code and existing JVMs (not too sure about the last one).
    So once again: Was the choice of not allowing static methods in interfaces a design choice or a technical choice?

    A better example of what you are suggesting is surely ...
    interface i {
        static void one();
    class a implements i {
        static void one() {
            // do something
    class b implements i {
        static void one() {
            // do something else
    }What would be the point of ever doing this?
    You cant call i.one() as the method doesn't exist without an instance of an implementing class.
    To actually ever be able to use that method you would effectively be casting an INSTANCE of a or b -> i. If you have an instance of an a or b then there is absolutely no reason for that method to be static.
    If you wanted to implement some sort of class (ie static) behaviour then class a could call its own internal static method from within the 'one' method.
    To get right to the point ... there isn't one. If it gets added to the language (and I can't see it in my wildest dreams) then Sun have lost their marbles, surely?
    Unless someone can give a good example of when it might be correct and useful to do so? I can't even see how it would be a convenience as it is completely unusable, no?

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • No static methods for Interfaces ?

    Hi,
    I was going though some documentation about the interfaces and it says that, an interface methods must not be static.
    Can someone please explain or direct me in the direction which tell me why the internet methods cannot be static.
    Thanx.
    Mel

    Defining a static method in a interface would be useless, since static methods can't be executed with dynamic binding. You'd have to know the name of the implementing class of the interface at compile time to call it, which would negate the need for an interface.
    For more details google it, that question has been asked thousands of times.

  • Static methods inside interfaces

    Why they are not allowed? Such methods would be very helpful in some cases. I speak, of course, about method declaration, not method definition.

    Ok , now I understand the problem. Thanks.
    And it's also impossible to override a staticmethod.
    Actually, it is very possible.Nope. That's hiding (or is it shadowing?), not overriding.
    The thing is, it only makes sense to have methods in an interface that can be overridden--by the JLS' definition of overriding--that is, where the particular method implementation that gets invoked is determined at runtime.
    Since static method invocatinos are compile-time bound, there's no reason for them to be in an interface--or indeed abstract at all, whether in an interface or abstract class.

  • Why is it that the interfaces cannot have static methods?

    why is it that the interfaces cannot have static methods?

    Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.

  • Interface with static methods

    I'm writting a wrapper for exception handling.One of the classes uses log4j to log exceptions.I want to write a interface to generalize loggin.Idealy I should have an interface with certain static methods for loging (i.e logError,logDebugMessage,consoleError,consoleMessage,etc) , but Interface dosent allow that and neither do abstract classes can havstatic method declarations.The implementations of these methods will achieve the hiding of the complexity of using a logging package,log levels etc from the user.
    Let me know how best I can work something out for this.
    Thanks in advance

    Define them once (as final) in an abstract class. Then any subclass can call logError etc.
    Kind regards,
      Levi

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

  • Why not static methods in an Interface

    why can't i make static methods part of an Interface?
    for example:
    public interface Names {
        public static String[] getNames(); // <--- "static" not allowed in an Interface.
    }what i want to say is:
    every class that implements the Names interface must have a static method, getNames() , that returns a raw array of Strings.
    why won't jave let me do this with an Interface?
    Edited by: kogose on Feb 4, 2009 5:47 PM

    this is my current solution:
    public interface Symbols {
        public String[] getSymbols();
    public class ETF implements Symbols {
        public String[] getSymbols() {
            return(ETF.symbols);
        private static String[] symbols =    { "DIG", "UYM", ...... }
    public class INDEXES implements Symbols {
        public String[] getSymbols() { return(symbols); }
        private static String[] symbols = { "^DZC", "^UTIL", "^GWI", .... }
    public class NYSE implements Symbols {
        public String[] getSymbols() {
            return(NYSE.symbols);
        private static String[] symbols =  { "GDL", "GDI", .... }
    }then to get the data:
    analyzer.analyze((new ETF()).getSymbols());
    analyzer.analyze((new INDEXES()).getSymbols());
    analyzer.analyze((new NYSE()).getSymbols());
    this looks like a hack to me?
    its weird that i create an object just to invoke one method and get static data.....
    is there an elegant way?

  • Re: static methods in an interface?

    You cannot define a constructor in an interface, (part of the language specification), and static methods belong to the class so how could a derived concrete class possibly implement something that belonged to its ancestor abstract class? Look at the factory pattern & perhaps Singleton for more guidance and seriously consider why you're attempting to do this. In fact, post the reasoning behind this decision and see if there are any useful comments / suggestions on that.

    This certainly sounds like a candidate for the Factory pattern, (or one of its specialisations such as Flyweight). Check out the forum here or one of the many sites focused on this area. You'll see that you're trying to solve a common problem in an unnecessarily complex way.

  • Static method allowed in interface?

    Hello,
    I've written the following code:
    package a.b.c.d;
    import java.util.Map;
    public interface Adapter
    public void execute(Mapping mapping) throws Exception;
    public static Map getParameters( ) throws Exception;
    My compiler complains thusly:
    "Adapter.java": Error #: 217 : modifier static not allowed here at line 8, column 23
    Is it illegal then to declare a static method in an interface and if so why? Thanks in advance!
    -Exits

    An interface itself is just a contract that says "I will implement thus-and-such methods with such-and-such a signature." The interface has no "meat" to it, so it can't implement the static.
    Now you're thinking, if MyClass implements MyInterface, then MyClass can just have a static method that is the one on MyInterface. The problem is with how you're getting your MyInterface-type object. You can do it like this:
    MyInterface obj = new MyClass();
    obj.myStaticMethod(); //Bzzzzzzzt! blows up at compile time...or...
    MyInterface obj = someMethodThatReturnsClassImplementingMyInterface();
    obj.myStaticMethod(); //Bzzzzzt! same problemYou can't call a static method on an instance; you have to call it on the class,
    MyClass.myStaticMethod();You can't call it on the interface directly because, again, the interface has no guts inside it. There's really no reason to put a static method on an interface because that's not what interfaces are for. If MyClass needs a static, put it there.

  • Interfaces and static methods

    Hi All,
    Does anyone know why you can't declare static methods in an interface? Is there a way round this problem?
    Cheers...

    But this won't:public class StijnsClass
      public static void aMethod()
        System.out.println("StijnsClass.aMethod()");
      public static void main(String[] arg)
        StijnsClass stijnsInstance = new StijnsSubClass();
        stijnsInstance.aMethod();
        System.out.println("Nothing else to say, here?");
    class StijnsSubClass extends StijnsClass
      public static void aMethod()
        System.out.println("StijnsSubClass.aMethod()");
        super.aMethod(); // Wrong!!!
    }You will get:
    "StijnsClass.java:21: non-static variable super cannot be referenced from a static context".
    If you remove static from the subclass method definition, you will get:
    "StijnsClass.java:18: aMethod() in StijnsSubClass cannot override aMethod() in StijnsClass; overridden method is static"
    That's the point. You aren't extending the method; you are only hiding it. To make it work, both methods must be instance methods, ergo, static methods cannot be extended.

  • Interface with a static method.

    I have tried to define an interface which requires a subclass to implement a static function.
    interface Testable {
    public static TestFrame getTestFrame();
    The idea is the the Testable object must be created with the appropriate constructer arguements, defined by the TestFrame. Thus the TestFrame must be created first.
    When I have tried this, the compiler complains that static is not allowed here.
    Is there a better way to do this?

    When I have tried this, the compiler complains that
    static is not allowed here.You can not have static methods in an interface - it would make no sense since static methods are not polymorphically overridden.
    >
    Is there a better way to do this?Since you need to know the class name in order to instantiate your object anyway, can't you just put the method in the class without it being part of the interface? - If the method is only necessary for object instantiation, then it doesn't sound like it belongs in an interface anyway - clients working with the interface type won't want to use it, so you're just cluttering up the interface.

  • Do the Interface contains static components like static methods and attribu

    Do the Interface contains static components like static methods and attributes ?

    >
    You have to supply a bit more detail: is that Lotus
    Notes API a Java API?Hmm, It's Java interface to Lotus Notes API
    Does it use JNI? Perhaps it is used somewhere underneath, I do not know for sure, but I think so
    Possibly the Lotus Notes
    implementation keeps a
    reference to those arrays, who knows?
    Maybe, but I'd be really suprised if it did. I derive this thread from Lotus Notes class and provide my own "worker method", overriding Lotus API abstract one, where I reference arrays. Arrays are specific to my program and since they are private fields in thread's class Lotus Notes layer does not have any way of referencing them, nor any reason for this matter
    For starters: if you zero out (set to null) your
    references to those arrays
    in your threads when the threads finish, there might
    surface a useful
    indication that you can blame Lotus Notes for this
    Well, I've become deeply suspect of whether these Notes' threads do really finish :-) My method finishes for sure, but it is just a part of run() method of Lotus Notes thread. Anyway, you can always safely blame Lotus Notes for almost anything :-)

  • Implementing interface with static method?

    Hi,
    I need to implement an interface with a static method. I tried to do it both with the interface method static and non-static, but it don't seam to work! Does it work?
    How can I make a work around?
    Thanks!

    Interfaces are designed to provide a contract that a particular object instance guarantees for it's Clients.
    Since a static method does not relate to any particular object instance there is no contract to define...hence you can't have an interface for static methods...
    What you could do however is return an object via a static method that does provide the implementation of the interface...
    i.e.public class MyClass
        static private String myInterfaceImpl = "<some class>";
        static public MyInterface getInterface ()
             return (MyInterface) MyClass.class.forName (MyClass.myInterfaceImpl).newInstance ();
    }That would return an object that provides the interface. I would presume you need the static method so that you don't have to pass around references to a particular object...this method gets around that...you could also create a single object at start up time and return a reference to that eveytime...
    Also, in a way static methods do define an interface...

Maybe you are looking for

  • Printing problem from Photoshop CS2 to HP 3500CP plotter

    I am running Photoshop CS2 on the computer connected to my 3500CP plotter. I have for the past few years had no problem printing. This past several days tried to proint a banner for my daughter's birthday and whenI go from Print with Preview to start

  • Did Leopard broke my built-in Airport?

    My network connections have been buggy since the upgrade. My airport scanner (or whatever it's called) is failing to see all the wifi networks around me including my own AEBS. This usually happens after waking up from a sleep. I have to resort to a r

  • Bootcamp problems on 24" Imac

    So I installed windows 7 ultimate on my 24" Imac 2.93GHZ with a Nvida GT 120. I installed the boot camp software on windows, which installed the graphics driver and everything. Anyway so I downloaded Dungeons and Dragons online cause I wanted to see

  • Problem with MPEG-4 video file in N70

    I wanted to transfer MPEG-4 video files from my computer to my N70 phone. I put the files to the same place where others videos are, and when I tried to watch MPEG-4 video it complained that the phone can't repeat it. I checked from nokia sites that

  • My Calendar App -

    In my Calendar app - I am trying to fill in an event that happened 2 months ago. The calendar app does not post it to my current calendar for those previous months.  What I am trying to do is use my calendar app as a journal and fill in information a