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.

Similar Messages

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

  • 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

  • Interfaces and class methods

    I want to implement an interface (to set common methods), but I want a method to be a class method of the concrete subclasses. Is there any way to do this? I cannot declare methods static in an interface. If I declare the method static in the concrete subclass this generates a compiler error.

    No I tried that! You cannot declare a class abstract and then declare the method abstract and static!
    I can create a method in the abstract class that is static and this can then be overwritten in the subclass, but there is no guarantee that the subclass implementer overwrites this method.
    Perhaps a redesign is in order. I don't think what I am trying to do is so obscure an interface means that you can be sure that the method is implemented, but this method is crying out to be a static method!

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Datacorruption and static methods

    public static void myMethod( String Argument)
         int i = 0 ;
    What are the chances of data corruption in this static method?
    IF there are chances of data corruption, am I corrupt in saying that chances of data corruption for argument and Variable i are same?
    Where is function state stored in static method stored? What will happen to this if one thread pre-empts other?
    public class a
         int j;
         public static void myMethod( String Argument)
              int i = 0 ;
    How is integer j different from integer i? Where will JVM keep these variables ?

    What are the chances of data corruption in this static
    method? None. As long as this static method only acts on local variables (variables declared inside the method) each call to the method is completely separate from any other call.
    Where is function state stored in static method
    stored? What will happen to this if one thread
    pre-empts other?I'm not sure what you mean by 'function state' but static methods are not associated with an Object, though they can modify and depend on the state of static (class) varaivbles.
    How is integer j different from integer i? Where will
    JVM keep these variables ? j is a member varaible. It is associated wth the instance of the class. i is a local variable and is created at the beginning of a method call and destroyed (eventually) after the method completes.

  • Generics and static methods

    Hi,
    I need a sanity check to make sure I have not missed design pattern.
    I believe that it is not possible to call a static method defined in a generic type.
    For example:
    public class Red extends Color
        public static Color getHue()
    public class Green extends Color
        public static Color getHue()
    public class GenericColorTest<C extends Color>
        public void fooBar()
             Color hue= C.getHue();  // Is this a valid method call ?
    }Since the base class Color can not define static methods, it seems resonable that a generic type can't make the call to get getHue(). Or am I missing something ? Is there a way for the class GenericColorTest's generic type C to call a static method ?
    Thanks
    HB

    I think I can be ever more specific than gafter on this.
    Your call, "C.getHue()", just plain makes no sense. C is "some kind of Color object", and the class "Color" has no function (static or not) called "getHue()". So calling "C.getHue()" is a simple case of you trying to call a function that isn't in the class.
    In fact you can call static functions, but only if they are in the base class require by the generic definition (erm, sorry can't remember the exact term right now). So, for example, if there was a "getHue()" static function in your class "Color", then sure, you can call "C.getHue()" in your code. But since static functions can't be overridden, the "C.getHue()" will do exactly the same thing no matter which actual class C was at the moment, which doesn't seem to be what you want.
    The right thing to do is just make "getHue()" non-static. Then things will work great.

  • Data Curruption and Static methods

    public static void myMethod( String Argument)
         int i = 0 ;
    What are the chances of data corruption in this static method?
    IF there are chances of data corruption, am I corrupt in saying that chances of data corruption for argument and Variable i are same?
    Where is function state stored in static method stored? What will happen to this if one thread pre-empts other?
    public class a
         int j;
         public static void myMethod( String Argument)
              int i = 0 ;
    How is integer j different from integer i? Where will JVM keep these variables ?

    Sorry The
    int j ;
    should have been
    static int j;
    I thought the behaviour of a variable in a static method will be same as static variable.

  • Nested interfaces and abstract methods

    Consider the following design:
    interface ZIF_INTERFACE_A.
      methods METHOD_A.
    endinterface.
    interface ZIF_INTERFACE_B.
      interfaces ZIF_INTERFACE_A.
      methods METHOD_B.
    endinterface.
    class CLASS_A_B definition abstract.
    public section.
      interfaces ZIF_INTERFACE_B
        abstract methods METHOD_B.
      interfaces ZIF_INTERFACE_A
        abstract methods METHOD_A.
      methods METHOD_C.
    endclass.
    class CLASS_A_B implementation.
      method METHOD_C.
      endmethod.
    endclass.
    When trying to implement this design, the syntax check is giving me an error:
    The method "METHOD_A" was declared as not ABSTRACT in a previous INTERFACES statement.
    If I implement the design with Java (either using a public nested interface, or using interface inheritance) there is no problem declaring both the methods METHOD_A and METHOD_B as abstract in the CLASS_A_B class.
    So it seems to me this might be a bug in the ABAP Objects implementation. Or perhaps I am missing something else here? Does anyone have any suggestions?

    Hello,
    Nested interfaces
    When you include an IF in another IF both of them will exist on the same level, there is no concept of hierarchy. So when you add interface ZIF_B in the implementing class ZCL_A_B, the interface ZIF_A is also "included" in the relationship with the class ZCL_A_B implicitly.
    Just try to activate the code below & you'll get the error: "Implementation missing for method zif_interface_a~method_a":
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
    *    INTERFACES zif_interface_a
    *      ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS: method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    So when the compiler is trying to compile your code it encounter implementation of ZIF_INTERFACE_B it finds that the "included interface" method ZIF_INTERFACE_Amethod_a is not abstract. So when you declare ZIF_INTERFACE_Amethod_a as "abstract" in the next line the compiler throws this error.
    So you need to define ZIF_INTERFACE_A~method_a as abstract, before defining ZIF_INTERFACE_B. Like this:
    CLASS class_a_b DEFINITION ABSTRACT.
      PUBLIC SECTION.
        INTERFACES zif_interface_a
          ABSTRACT METHODS method_a.
        INTERFACES zif_interface_b
          ABSTRACT METHODS method_b.
        METHODS method_c.
    ENDCLASS.                    "CLASS_A_B DEFINITION
    In this case the compiler treats method_a as abstract while checking ZIF_INTERFACE_B. Hence it doesn't throw any error.
    Hope i'm clear.
    BR,
    Suhas
    PS: Whenever i face any problem while creating local classes, i create a dummy class in the class builder to check

  • Regarding Returning Parameter and Static method

    Hi frnds,
    I am learning oops ABAP. I want to use returning parameters in method and also STATIC METHOD.
    If any example it will be more helpful
    regards,
    satya

    Hi satya,
                 Check this out ,Its helpful.
    To get some values from a method , one can use the exporting, changing or returning parameters.If one uses RETURNING parameters, the following restrictions apply:-(1) No EXPORTING/CHANGING parameters can be used for the method.(2) Only one RETURNING parameter can be used.(3) RETURNING parameters are only passed by value.This program demonstrates the use of RETURNING parameters and the various ways   to call a method with RETURNING parameter to get the value into some variable.
    Sample Program
    </code>
    report ysubdel1 message-id 00.
    data : w_num type i.
    class c1 definition .
    public section. 
    methods : m1 importing input1 type i
                            input2 type i
                            returning value(result) type i .
    endclass.
    class c1 implementation.
    method  : m1.
    result = input1 * 2 + input2.
    endmethod.
    endclass.
    start-of-selection.
    data : obj1 type ref to c1 . 
    create object obj1.
    Syntax 1     
    call method obj1->m1 EXPORTING input1 = 5                                                        input2 = 4  
                                   RECEIVING result = w_num.  
      write:/5 w_num .
    Syntax 2
         w_num = obj1->m1( input1 = 10 input2 = 20 ).
      write:/5 w_num .
    Syntax 3     
    move obj1->m1( input1 = 2 input2 = 3 ) to w_num .  
    write:/5 w_num .
    </code>
    Static method example
    <code>
    REPORT  zstatic.                              .
    data : num type i.
    class testclass definition.
    public section.
      class-methods : testmethod.
    endclass.
    class testclass implementation.
    method : testmethod.
      num = 5.
      write:/5 num.
    endmethod.
    endclass.
    start-of-selection.
    call method testclass=>testmethod.
    </code>
    Reward Points if u find helpful.
    Thnks & Regards,
    Rajesh

  • Interfaces and static

    Hi all
    How can I declare a static method as part of an interface? None of the documentation sugests that this is not possible yet the complier wont let me put the static keyword in.
    cheers
    Stephen Whipp

    Oh well, guess I'll just have to live with creating pointless instances then.Don't dispare:
    interface Chix {
        public void someMethod();
        final class Dig {
            private Dig() {} //not for instantiating
            public static void git() {
                System.out.println("oh yeah");
    //Chix.Dig.git();

  • Synchronized and static methods

    I've got a doubt: is it possible to apply syncrhonized to a static method? I know that synchronized takes a lock on the current object, but in the case of a static method there could be no object.
    So how can I synchronize a static method?
    Thanks,
    Luca

    previous X POST(s) :
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411296
    http://forum.java.sun.com/thread.jsp?forum=31&thread=411285
    http://forum.java.sun.com/thread.jsp?forum=31&thread=390499
    http://forum.java.sun.com/thread.jsp?forum=31&thread=374388
    http://forum.java.sun.com/thread.jsp?forum=31&thread=325358
    BOTTOM LINE : Search the forum b4 posting.
    rgds.

  • Polymorphism and static methods

    Say I have classes A and B:
    public class A {
         public static A newInstance() {
              return new A();
    public class B
    extends A {
    }How can I write the newInstance method in A so that:
    B.newInstance();returns an object of class B instead of A? I know I can override the method in B to make an object of the right type - but is there a way to write the A method so that the correct type is created by any subclasses?

    I suppose this is cheating...
    class A {
       public static A newInstance(Class c)
       throws InstantiationException, IllegalAccessException {
          return (A) c.newInstance();
    class B extends A {
    class Testx {
       public static void main(String[] args)
       throws InstantiationException, IllegalAccessException {
          B b = (B)B.newInstance(B.class);
          System.out.println(b.getClass().getName());  //B

  • Completely stuck, get/set, Contructors and Static Methods

    Hi any help would be very appreciated on this one,
    import java.util.Scanner;
    import java.io.*;*
    *import java.util.*;
    public class Course extends Program {
         public Course(String Coursecode, String Coursename){
              Coursecode = stuinput.courseCode;
    public void getCoursecode(){
         return stuinput.courseCode;
    //public String getCourseCode(){
    //     return this.courseCode;
           public static void printCourses() throws Exception
                stuinput[] courseObjArray = new stuinput[18]; //Make sure this is the same as the ammount in the text
                   Scanner sc = new Scanner(new File("courses.txt"));
                   int i=0;
                   boolean found = false;
                   while(sc.hasNextLine())
                   //Delimit this line with scanner
                   Scanner sc1 = new Scanner(sc.nextLine());
                   sc1.useDelimiter(":");
                   courseObjArray[i] = new stuinput(sc1.next(),sc1.next());
                   i++;
                   }//while
                   for(int i1 = 0;i1 < courseObjArray.length;i1++)
                   System.out.println(courseObjArray[i1].courseCode);
                   System.out.println(courseObjArray[i1].courseName);
                   System.out.println("-----------------");          
           //This print the indexOf what you want to search
              class stuinput
              String courseCode = null;
              String courseName = null;
              stuinput()
              stuinput(String courseCode,String courseName)
              this.courseCode = courseCode;
              this.courseName = courseName;
    import java.io.*;
    public class gradCheck {
         public static void main (String args[]) throws Exception {
                      Course.printCourses(); //Prints All Course but dont need that
    }This ^^^ Is basically the driver class, Im trying to run the printCourse() from the 1st Class I posted.....but it's giving me lots of errors with everything I try, I'm trying to get the values out of that text file and have them broken up so I can use them amoung various class's, I want to use those values inside the Course class, as well as the Program Class and other Class's that extend off of that,
    Any Ideas (im sure there are because im very new), as to how I might to that
    Thanks :-) would be much appreciated

    yes, I still have a lot to learn here I think, Thank you so much, that worked for me, I think I need to read a lot about all of this and understand it......thank you
    If I may, one more thing which I'm really stuck on and if I can get this right, I think my whole program and ideas will just fall into place...Ive been trying to a couple of weeks now and can't quit get it right
    in the above code,
    this bit,
              class stuinput
              String courseCode = null;
              String courseName = null;
              stuinput()
              stuinput(String courseCode,String courseName)
              this.courseCode = courseCode;
              this.courseName = courseName;
              }how do I pass this off to another class through the constructor
    public class Course extends Program {
         public Course(){
         }at the top....say If I want it to be used in the Program class.......or a student class that extends of the this current class above (Course Class)
    Thanks,

Maybe you are looking for

  • Link from Accounting Doc Number to PO

    Hi, In FBL3n certain doc types PO number is not updating.Using assignmnets i want to update the field for these kind of doc no. My doubt is from FI doc number how can i link it to the PO number. Eg:i have an FI doc number say 51000000 which has two l

  • Still needs a bit of work (apple take note)

    I love this - it is amazing and it is helping me out loads.... However, there are glitches with syncing data (there are work-arounds) and Apple need to sort these and make it easier to re-submit your data. Probably the worst for me was tonight....jus

  • Ship To address changed in SO, is it updated in Delivery?

    Sales order is created, delivery is created. Then in VA02, in sales order header level, Tab Partners, ShipTo Street/House No. is changed. Does this change go through to the delivery automatically? Please help, Typewriter

  • Keynote file (OSX 10.9.5) does not show up in iCloud drive

    I have created a keynote presentation, using OS X 10.9.5, saving it in iCloud. The next day I wanted to continue to work on the presentation. But it does not show in iCloud Drive, whereas Keynote states, that the file is stored in iCloud Drive. That´

  • Calling a .dll from a LOCAL applet… I'm doing something wrong

    There should be no security restriction because the applet is locally installed. Yet I get: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.jzmq) when my app tries to call static{      System.loadLibrary("