Interfaces: static variables but instance methods, why?

Why do variables need to be static in interfaces but the methods in them are not allowed to be static? Or, asked differently: Why methods must not be static while variables have to be static in interfaces?
I don't understand the reason for that difference.

An interface defines functionality but can not be instantiated as an object. So for the static variables, it can define variables that can be accessed by all implementing classes, but there can only be one definition of them, hence static. Non-static variables fall in the realm of implementation, which is not what interfaces are for.
Static methods are used to define an implementation that is common among all instances of an object, and must be implemented when defined. Since interfaces can not provide any implementation, static methods are invalid. Remember that static methods are commonly used without instantiating an object (like java.lang.Math methods) so the implementation must be provided when defined.

Similar Messages

  • Write to static field from instance method

    instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
    public static loadingDialog StatusWndw = null;
    StatusWndw = new loadingDialog(this);
    iwant to acces this satic field out side the class.
    how to slove this problem

    Make the LoadingDialog a singleton class. Lookup the singleton pattern.

  • Can one combine static and instance methods?

    Hi,
    Can one define a method so that is can be used as both a static or an instance method?
    Basically I'm trying to simplify my class to so that I can call a method either statically with parameters or instantiated using it's own attributes.
    In other words, I'm trying to accomplish both of these with one method:
    zcl_myclass=>do_something_static( im_key = '1234' ).
    lv_myclass_instance->do_something( ).   " key in private attributes
    Why would I want to do that?
    I would like to avoid instantiation in some cases for performance reasons and would like to keep it simple by having only one method to do basically the same thing.
    Any input or alternative suggestions welcome.
    Cheers,
    Mike

    Ok, I may be reaching here a bit, I know, but maybe this may give you some ideas.  After creating the object, pass it back to the method call.
    report zrich_0001.
    *       CLASS lcl_app DEFINITION
    class lcl_app definition.
      public section.
        data: a_attribute type string.
        class-methods: do_something importing im_str type string
                                   im_ref type ref to lcl_app optional.
    endclass.
    *       CLASS lcl_app IMPLEMENTATION
    class lcl_app implementation.
      method do_something.
        if not im_ref is initial.
           im_ref->a_attribute = im_str.
          write:/ 'Do_Something - ',  im_ref->a_attribute.
        else.
          write:/ 'Do_Something - ',  im_str.
        endif.
      endmethod.
    endclass.
    data: o_app type ref to lcl_app.
    start-of-selection.
      create object o_app.
      call method o_app->do_something(
               exporting
                   im_str = 'Instansiated'
                   im_ref = o_app ).
      call method lcl_app=>do_something(
               exporting
                   im_str = 'Static' ).
    Regards,
    Rich Heilman

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Static variable access

    Hi everyone,
    Just a quick question:
    In the following piece of code, why does the compiler NOT complain about non-static methods accessing a static field?
    public class Plane {
       static String s = "-";
       public static void main (String[] args){
           new Plane().s1();
           System.out.println(s);
       void s1(){
           try{
               s2();
           catch(Exception e){
               s += "c";
       void s2() throws Exception{
           s3();
           s += "2";
           s3();
           s += "2b";
       void s3() throws Exception{
           throw new Exception();
    }

    Can anybody explain a little more about what happens
    when static classes are compiled, or point me in the
    direction of some reading material please?
    I would like to know the difference between static
    variables and standard variables at compile time. I
    am confused because I would have thought that if
    there is a declaration in the code then the compiler
    knows that that object will exist.
    ThanksWhen the class loader loads the class, that's when static instances are created and when static blocks of code are executed. A java Class is actually an Object like any other, so you can think of static variables as instance variables for the Class object, and static blocks of code are somewhat like constructors for the Class object (in the sense that the code is executed when the class is loaded by the class loader).
    Individual instances of the object share the class' static variables, but non-static variables are only available to the instances. So the class 'instance' (which was loaded by the class loader) can't access non-static variables because non-static variables don't exist until you create an instance of the class.

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

  • Static variable and non-static

    I have a quick question. The following syntax compiles.
    private String t = key;
    private static String key = "key";
    But this doesn't compile.
    private String t = key;
    private String key = "key";
    Can anybody explain how it is treated in java compiler?
    Thanks.

    jverd wrote:
    doremifasollatido wrote:
    I understand that completely. I didn't say that the OP's version with static didn't work. I was just giving an alternative to show that you don't need static, if you change the order that the instance variables are declared.My problem with the underlined is that, while technically true, I can see where a newbie would take it as "oh, so that's how I can get rid of static," and focus only on how to satisfy the compiler, rather than on learning a) when it's appropriate to make something static or not from a design perspective, and b) what the implications of that decision are, for both static and non.
    I have just a wee bit of a prejudice against the "what do I type to make the error messages go away" approach. :-)That sounds good to me. We're currently trying to fix an issue caused by the fact that one class has most of its variables as static, when they should really be instance variables. There should only be one active instance of this class at a time, but the values of the static variables stick around when you call "new ThisClass()". So, old data interferes with new data, and various errors happen. The class has many static methods to access the static variables, but it should have been more of a Singleton--an actual object with non-static variables. The active instance of the Singleton would need to be replaced at logout/login (as opposed to shutdown completely and restart the JVM), but then at least when the new instance were created, then all of the variables would be initialized to empty--the old instance would disappear. The solution at the moment (solution by others--I don't agree) is to clear each static Vector and then set the reference to null (setting to null would be enough to drop the old data, but certain people don't get that...). This is fragile because many variables were missed in this "cleanup" process, and it will be easy to forget to "cleanup" new variables in the future. This class has been misdesigned for years (much longer than I've been here). The calls to static methods permeate the application, so it isn't easy to fix it quickly. There are several of these misdesigned classes in our application--a mix of static and non-static, when nothing or almost nothing should be static.

  • How to give different value to a static variable???

    Hi all:
    Is there any solution to set different values to a static variable???I had try two ways but all have errors!
    1.Way_1
    protected String tmp=null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    tmp = "string1";
    else if (sayorpress==1)
    tmp = "string2";
    protected static String RESOURCE_STRING = tmp; <---error
    Error:non-static variable tmp cannot be referenced from a static context
    2.Way_2
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    protected static String RESOURCE_STRING = "string1"; <---error
    else if (sayorpress==1)
    protected static String RESOURCE_STRING = "string2"; <---error
    Error:illegal start of expression at
    not an expression statement at
    Thank you very mich!!!

    Try this:
    protected static String RESOURCE_STRING = null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    yourClass.RESOURCE_STRING = "string1";
    else if (sayorpress==1)
    yourClass.RESOURCE_STRING = "string2";
    You cannot declare a static variable inside a method. But you can access a static variable thorugh your class.

  • Is is better to use static variables?

    Hi,
    Does anyone know if it's better to use static variables or to use normal variables?
    Concerning the size of the code, it seems that declaring a variable as static is more consuming (for example plus 6 bytes for an object reference).
    So this could mean that declaring variables as static should be avoided, but what about the execution time?
    Some years ago, some javacard gurus were claiming that it's was better to use static variables (less processing required by the JVM to resolve adresses of static variables), but is it still the case?

    Hi Lexdabear,
    Thanks for the answer.
    I did the test (I converted my all code to use static variables and methods as much as possible), and did a bench before and after, on a JCOP31 card.
    The conclusion is that today JVMs and processors are much powerful than 5 years ago, and that the difference is really difficult to measure, which anyway is a good thing for us ;-)

  • This static method cannot hide the instance method from...

    What means the error message "This static method cannot hide the instance method from Referee"?
    Referee.java is a interface. I implemented it in the class RefereeMyName.java and made a method in that class to be static. Thats why I received that error message.
    But can't I use static methods when I have implemented a interface in that class? I want to have a Player.java class which I want to access RefereeMyName.getTarget(). I cannot use a instance instead because I wouldn't receive a valid return value then (RefereeMyName is the client class).
    What is the solution?

    Hi,
    Well i do not think that you can do that b'cos that way you are not giving the same signature for the method as that exists in the interface. I do not know how other way it can be done but if something urgent for you then you can remove that method from that interface and only define in the class.
    Regards,
    Shishank

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • Purpose of declaring the method or class or static and as instance

    what is the purpose of declaring a method in a class or the class itself as static.
    Does it mean we cannot create a copy of that class or method if we declare it as static.
    if so then why do they dont want that class to be created as a copy ?
    Why do they want to declare a class as static
    please provide some conceptual undersatnding regarding the static and instance class with one example

    Static methods are often used for the implementation of utility methods. Please have a look at the class CL_ABAP_CHAR_UTILITIES for example.
    You use the methods of this class in the same way as you would use a function in ABAP (like
    LINES( itab )
    ). You use it in a static way because the functionality is always the same no matter in what context you are calling the function.
    The purpose of instance methods is that their logic is in some way related to an attribute of the object instance that you use to call it.
    For example, you create an instance of object PO (a purchase order) called MY_PO. Then the method
    MY_PO->ADD_POSITION
    would add a position to a concrete PO that has a unique number etc. But if the object has a static method DELETE_POSITION then it just deletes the current position of a PO, regardless on which concrete PO you are acting at the moment.
    I hope this clarifies it for you.
    Regards,
    Mark

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belief.
    But in Java, it's easy enough to declare an instance variable public thus eliminating the need to write accessor method. What's the rational behind this feature? Is it merely to save developer some time from typing in the accessor methods? Does this reason justify the use of public members?

    I know some OOP purists believe all instance variables
    should be private, ALL? No way!
    and if there's a need to view or
    set the value of these instance variable, public
    accessor methods need to be created. There has to be a reason for any :- public int getMyInt(){ ...
    and in many cases protected or default package is more appropriate
    Data
    encapsulation is the driving force behind this belief.
    Correct , also avoiding multiple instances of member states - very often its a control issue too
    But in Java, it's easy enough to declare an instance
    variable public Yes and its also easy enough to write shittie code too ...
    if an instance variable is public there should be a clear comment explaining why the field has to be public
    thus eliminating the need to write
    accessor method. There's nothing wrong with accessors and mutators - the java language is full if them
    What's the rational behind this
    feature? As you stated encapsulation
    Is it merely to save developer some time
    from typing in the accessor methods? This is a lame reason
    Does this reason
    justify the use of public members?and attract unwanted side effects?
    I also don't like to see (or to write) a huge long list of getters and setters at the bottom of any class file and find it quite ugly - You should use them when you need to, not as a matter of routine.
    Accessor - mutator is a design issue for private instance variables that you wish to keep hidden. Your suggestion to make them all public is also a design issue and if I was to see a long list of public variables at the beginning of a class (unexplained with javadoc comments) I would be very puzzled indeed.
    Eclipse will automate the generation of accessors and mutators for you and also has a refactoring tool too - both are extremely useful

  • Interface member variable by defaultly static ?

    Hi,
    The interface member variable by defaulty public,static,final.
    But i have one doubt.
    It is public because it has to access out side the interface.
    It is final because the value never changes
    Why it should be static ???
    Thanks,
    Narendra babu.B

    Member variables are an implementation detail. Java does not allow multiple implementation inheritance. Java does allow multiple subtyping through interfaces. So interfaces can't have member variables.
    Consider the diamond of death:
    interface A
        int x;
    interface B extends A
    interface C extends A
    interface D extends B, C
    }See the problem now?

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

Maybe you are looking for

  • What is best windows compatible web share format once and for all?

    Wmv looks good, but I don't want to buy flip4mac studio. The other formats I have tried look bad and are huge files. I have searched forum for answer in vain.

  • Quicktime not playing videos online

    so, i'm trying to watch a video online using quicktime, but everytime i try to watch it, i get a the quicktime Q with a question mark. I've updated to the new version and updated adobe flash player, but its still not working. Is there a problem with

  • Pourquoi mes périphériques sont déconnectés en sortie de veille

    Bonjour, Depuis peu possesseur d'un IMAC, je m'étonne de certains problèmes apparaissant sur MacOS, que je n'avais pas du tout sur windows. J'ai mis un hub USB sur l'un des ports USB du mac, un récepteur pour manette xbox360, mon imprimante. Sur le p

  • Column link image

    In my report source I have following column source: case when iv.email is null then '<img src="#IMAGE_PREFIX#pkt_mailto.gif">' else null end email It behaves as I expected. But I need to have link on the images shown. So I set as link text for this c

  • Restriction for tag name and column name

    It seems that the XML tag name has to be the same as the corresponging column name when using xmlgen.insertXML. Is there any plan to relax this restriction? null