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?

Similar Messages

  • 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.

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • 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.

  • Why are static methods called with null references,valid ?

    This is my code :
    package inheritance;
    public class inh6{
         public static void method(){
         System.out.println("Called");
         public static void main(String[] args){
              inh6 t4 = null;
         t4.method();
    O/P :
    CalledHere t4 is a null reference and yet we are able to call a method on it,why is null pointerexception not thrown.Why are we able to call static methods using null references ?
    t4 is null means it doesnot refer to any memeory address,hence how is method() called correctly.
    I hope i am clear. :)
    Thank you for your consideration.

    punter wrote:
    jverd wrote:
    Memory addresses have nothing to do with it. I doubt memory addresses are even mentioned once in the JLS.
    By memory address i mean the memory location the reference is pointing to.I know what you mean. But if you think it's relevant, can you show me where in the JLS it says anything about memory locations?
    >
    You can do that because a) t4's type is "reference to inh6" and b) method() is declared static, which means that you don't need an object to call it, just the class. That class comes from the compile time type of t4. The fact that t4 is null at runtime is irrelevant.
    So at compile time the type of t4 is inh6 and hence the method is called.Is it ? Had method() not been static a NullPointerException would have been thrown.Correct.
    With non-static, non-private, non-final methods, which implementation of the method gets called is determined at runtime, buy the class of the object on which it's being called. If any one of those "non"s goes away, then the method is entirely determined at compile time, and in the case of static methods, there's no instance necessary to call the method in the first place.

  • Static method or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • Map - why  not a part of collection interface

    Pals,
    Why Map is not a part of Collection interface. This was a question asked to be inteh interview.
    I answered that it based on key value pairs thats y its not a part of collection interface. Dunno whether this is correct or not
    Benji

    And you could have scored some points if you casually mentioned that views of Map<K,V> do present collections:
    Set< Map.Entry <K,V> > entrySet()
    Set <K> keySet()
    Collection <V> values()

  • Why not compile error on "incompatible interface cast"?

    simeple code here
    class IncompInterfaceTest {
    void doTest() {
    ClassB b = new ClassB();
    InterfaceA a = (InterfaceA)b;
    interface InterfaceA{}
    class ClassB{}
    javac issues "ClassCastException" on runtime rather than compile
    error.
    as i know incompatible type casting may be caught at runtime and
    compiler shows the error.
    but why compiler doesn't do it's job for interfaces? it's just so
    clear to be compile error to me.
    ps. in a case ClassB is final class, compiler issues a error.
    (a thread I started in google groups)
    http://groups.google.co.kr/group/comp.lang.java.programmer/browse_thread/thread/c9c12a8864672436?hl=ko#

    sun9h0st wrote:
    thanks for reply.
    I think i might know something wrong about class, object concept, so I wish you tell me more about it.
    As I though the code below means
    ClassB b = new ClassC();'b' can be an Object of ClassB as a subclass of ClassC.
    'b' IS an Object of ClassC.b is not an object.
    b is a variable that can point to an instance of ClassB or to an instance of any subclass of ClassB.
    >
    so
    b instanceof ClassB == true // as it can be
    b instanceof ClassC == true // as it is
    If b is not null, the first line will always be true.
    If b points to a ClassC or a subclass, the second one will be true.
    It means actual Object(something behind 'b' pointing, i don't know what i call it) is from ClassC to me. (somewhat like c pointer,
    'b' is a bowl that called Object and actuall instance is refered by 'b')No idea what you're saying here.
    if b IS an Object of ClassB
    shouldn't "b instanceof ClassC" is false?If we have C extends B, then...
    B b1 = new B();
    B b2 = new C();
    b1 instanceof B // true
    b1 instanceof C // false
    b2 instanceof B // true
    b2 instanceof C // true
    I Think compiler should be known that instance 'b' hold. No, it doesn't, and it's good that it doesn't, as it keeps the language simpler and more consistent.
    Also, b doesn't hold an instance. It holds a reference to an instance.

  • Why have static methods?

    What is the criterion to decide whether a method should be static or not?

    lets say you have a class called Utility. No other class ever needs an instance of Utility becuase all of it's methods are static and the class is public. Example:
    package com.abc.util;
    /* make it final so can't extend */
    public final class Utility
       /* can't call new Utility now */
       private Utility()
       /* these methods below, by just seeing their names, should be static */
       public static long ipStringtoLong(String address){}
       public static String execShellCMD(String shellCMD){}
       // ect ...
    }Now a class can import and use it. There are no instances associated with these methods except the values passed to them. It makes them accessable from anywhere in your application w/o worrying about having a ref to an Object. Their accessable as long as the class can be found in your class path. Jar'em up and put them into C:\jdk1.xx\jre\lib\ext\util.jar
    import com.abc.util.Utility;
    // ........(String host, String port){
       long ipLong = Utility.ipStringToLong(host);

  • 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.

  • 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.

  • Benefits of static methods?

    Why use static methods is it because memory is saved because a new instance is not required for each use?

    First of all you have to know, that creating instance of object is one of most expensive operation in java execution. Second, sometimes you don't need to have any state information within object, for example you'd like to write method to add two integer numbers given as parameters. Static methods are known also as Class methods, there is only one such method for all instances of class. Static methods are very usefull and convinient ! There are more and more reasons to use static methods !

  • 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.

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

Maybe you are looking for

  • I am running windows 8.1 but want to use the desk ...

    I am running windows 8.1 but want to use the desk top version of skype. When I try to install the latest version of skype I get the following message "A Previous program installation was never completed. You need to restart your computer to complete

  • Where can I get an implementation of the interface java.sql.Savepoint

    My hibernate app fails BUILD FAILED: java.lang.NoClassDefFoundError: java.sql.Savepoint" I've no idea why it fails on one machine but passes on another, same JVM version, same hibernate version

  • Fetching from LDB PNP - Performance Issue

    Hi, My apologies if my question sounds too basic, but i have not worked in HR earlier. So just needed to clarify once. I've researched it well on SDN , then created a solution but just wanted to check with you guys once, if this the the correct way i

  • Facebook display pictures don't sync

    I have just updated to both iOS 6.0 and OSX 10.8.2. The problem I have is that, when I add my Facebook account to both my Mac and iPhone and press "Update Profile Photos...", it returns "Updated 0 contacts" and my contacts are not updated. I'm not su

  • Storage types

    Hi All The user requirement is M-MATERIAL If the material is received through AIR(aeroplane) it has to follow one storage type search strategy and if the procuremnt is through road transportation  it has to follow another strategy. For eg: Through Ai