Forcing implementation of an inherited static method/field?

Suppose I have some classes - BlueAction, RedAction etc - extending an abstract base class called BaseAction. I put an abstract method called getColour() in BaseAction, and implement it in all the classes that extend it, so BlueAction returns blue, and so on. Fine.
I now want to use a class loader to get their colour, but crucially, I don't want to instantiate them, so instance methods are out.
If you could declare abstract static methods, I'd do that, and be assured that every implementation of BaseAction contained the necessary info. Obviously you can't do this.
I think I could just put a static method or field in each one, and access that via something like Class.getField("COLOUR")but then there's nothing to force me to put that code into each implementation.
Is there anything clever I can do?
Cheers,
Rob
Edited by: arewenotmen on Jun 20, 2008 3:51 AM

baftos wrote:
I guess it should be possible. Me, I did play with runtime annotations, but I am scared like hell
of compile time annotation. My reasons, but maybe I am wrong:All good reasons.
- Modify the build process to use APT instead of javacYou could use in -nocompile mode and add a task to the build script.
- Writing annotation processors, big overheadI had a play, was not too hard to get started with, but then it started to get wierd and data I expected was not being returned.
- Using com.sun classes in the processors instead of java/javax classes (subject to change?)Java 6 has the javax.annotations package (also works with javac rather than a different tool), but this seams less powerful than apt.
A fair few things now mean the "don't touch the com.sun package" rule is being eroded. The httpd is in it as well.

Similar Messages

  • Why is it necessary to create an instance via the static method?

    Hi,
    For some classes (such as java.util.regex.Pattern), we should call the class method (static method) in order to create an instance (object).
    For example, in order to conduct the pattern matching, we should use the java.util.regex.Pattern class as follows:
    Pattern p = Pattern.compile ("X[0-9]+X") ;
      // An instance of the Pattern class is created.
    Matcher m = p.matcher ("abcX1XYX23Xz") ;
    while ( m.find() ){
      System.out.println ( m.start() ) ;
    }where the compile static method in the Pattern class creates an instance and returns the pointer (reference) of it. We should NOT call
    the constructor of the Pattern class as follows:
    Pattern p = new Pattern ("X[0-9]+X") ;    // ERRORThe question is the following:
    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?
    (2) Why do the java.util.regex.Pattern class have such a specification?
    Thanks in advance.

    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
    2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
    3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
    "This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
    Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM

  • Synchronized static method -is there a problem?

    Hi.
    I'm facing a problem. I have a common java class that is used by many applications. Class is in a jar file and is in server's shared library. And every applications in the server used it.
    Methods are declared static but not synchronized static. Class itself is not static. I have found that sometimes right after server is restarted and applications are using this class, method return values are mixed up or method behaviour is strange. I havent able to repeat this problem when testing with just one application.
    Is the problem static method and when using under one classloader (in shared lib) probelm occurs? So if i declare it static synchronized, does that solve my problem?

    Ok. But is it still risk to use static classes or
    static methods/fields in class that are shared with
    multiple applications ie. in servers shared library?That's a big fat YES.
    I suspect that you might benefit from investing a couple of hours in the "concurrency" tutorial
    http://java.sun.com/docs/books/tutorial/essential/concurrency/

  • Reflextions within static methods

    I need to know the name of the class within a
    static method.
    In an instance method I can just use
    this.getClass(), but not in a static method.
    I need it because I have a class that inherits
    from a singleton. But I can't use the inherited
    static method getInstance(), it gives me
    in instance of the superclass.

    I don't want to overwrite "instance" and "getInstance()",
    I only want to use them in the context of the Class "Something".
    Here is my next approach to the Idea:
    abstract public class Singelton {
         static Singelton instance = null;
         static Singelton getInstance(Class thisClass)     {
           if(instance == null)
              try {
                Constructor constructor = thisClass.getConstructor();
                instance = (Singelton)constructor.newInstance();
             } catch (Exception e) {
              e.printStackTrace();
           return instance;
         abstract public void doSomething();
    public class Something extends Singelton {
         public void doSomething()
              System.out.println("Hello world!");
         public static void main(String[] args)
              Singelton s = Something.getInstance(Something.class);
              s.doSomething();
    }The only little thing is, I would like to avoid
    the parameter "thisClass" in the method "getInstance()",
    because the method getInstance() in the class Singelton
    is call thru the class Something.

  • What's the differences between a singleton and a class with static methods

    Hi everybody.
    My question is in the subject. Perhaps "differences" is not the good word. The positive and negative points ?
    Imagine you have to write a connection pool, sure you gonna choose a singleton but why ?
    Thank you very much.

    A class is a class. Java doesn't have (and I wish it
    did) a static outer class. Any class can extend
    another class or implement an interface.A Class object cannot extend or implement anything - it is not under programmer control in any way. You can create a class which implements interfaces, but calling static methods is completely unrelated. Interfaces only affect instance methods, not class ones. I think all of your comparison to C++ is actually confusing you more. In Java, there is a real class object at runtime, as opposed to C++.
    YATArchivist makes a good point about being able to
    serialize, altho I've not met that desire in practice.
    Maybe a concrete example would help.
    mattbunch makes another point that I don't understand.
    A class can implement an interface whether it sticks
    its data in statics or in a dobject, so I guess I
    still don't get that one.See my comment above. Static methods are free from all contractual obligations.
    I prefer instance singletons to singleton classes because they are more flexible to change. For instance I created a thread pool singleton which worked by passing the instance around, but later I needed two thread pools so I made a slight modification to the class and poof! no more singleton and 99% of my code compiled cleanly against it.
    When possible, I prefer to hand the instance off from object to object rather than have everything call Singleton.instance() since it makes changes like I mentioned earlier more feasible.

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Forcing static method implementaion!!

    hi guys,
    I want to force the implementation of a static method in my subclasses! How can i do it?

    thnks!!
    I wanted write some classes , each take a
    different type of document (html, word, etc.,) and
    give back the text file. thts all the work they shud
    do , and i want them to have a same signature!! and
    make sure any future addition of types ( with new
    java classes) , i shud have the same signature!!That still doesn't explain why you want to have static methods. The methods shouldn't be static, and you should create an interface.
    Kaj

  • Custom Taglets and static class fields/methods...

    Hey all,
    I have a curiosity question (running winxp + j2sdk 1.4.2_04).
    I have written a few stand-alone and inline taglets to help me document my code. I had some problems initially getting the HTML to output correctly (and I don't know how to run javadoc in the debugger) so I wrote a simple class with only static methods/members that tracks the nesting level of the current tag and allows me to pad (prefix) the output based on the nesting level (rudimentary I know). I wasn't sure if the javadoc process was multi-threaded or not, so all methods are synchronized.
    My problem is that the static initializer is being called 6 different times during the execution of javadoc.exe, resulting in what I would term as 6 "static" instances. Now, the only reason I can think of for this is that it is spinning off new process for each type of taglet it encounters. However, processing seems sequential and I don't see any other processes in Windows Task Manager. Here is the static initializer code:
         static {
              ic = new IndentControl();
              System.out.println("static: " + Thread.currentThread() + " ic instance: " + ic);
    and here is the output of javadoc.exe:
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@33c78b
         Registered Taglet ndstest.util.javadoc.MandatoryTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@6c137c
         Registered Taglet ndstest.util.javadoc.OptionalTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@1104da7
         Registered Taglet ndstest.util.javadoc.MemberInlineTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@6745b9
         Registered Taglet ndstest.util.javadoc.DescriptionInlineTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@10a14ad
         Registered Taglet ndstest.util.javadoc.ExampleTaglet ...
         static: Thread[main,5,main] ic instance: ndstest.util.javadoc.IndentControl@1afe460
         Registered Taglet ndstest.util.javadoc.ToDoTaglet ...
    Why does the static initializer get called 6 different times? It's mildly annoying and I want to understand why and if it is something I am doing to cause this.
    Thanks!

    Well, have you ever taken a look at the implementation of the Standard doclet? (Its source code is part of the SCSL distribution.)
    The current implemenatation uses a TagletManager to handle/store/load custom taglets.
    For each -taglet option, method addCustomTag of this TagletManager is called.
    This method creates a new instance of UrlClassLoader and uses loadClass( className ) to load the taglet each time it is called.
    So, each of your six taglets is loaded through/in a different ClassLoader context, therefore the static init block is executed six times.

  • Implementation of static methods in Custom Controls

    I'm using Custom Java Controls to implement business objects in a workshop web application.
    I've designed a number of static methods into the object model for logically static operations (i.e. operations related to the Business object but not requiring an instance).
    Since workshop generates the control interface as a java interface, it is not possible to declare static methods on the control interface. I have tested implementing the interface as an abstract class and setting @editor-info:code-gen control-interface="false" on the control. This seems to work, but then we lose code generation.
    Other options include:
    - Put the static method on the Impl and call directly (don't like this, breaks encapsulation)
    - Make it non-static (don't like this, prevents compiler checks for refs to non-static members)
    Has anyone found an elegant way to do this in workshop without losing code gen features? Any ideas welcome...
    TIA
    Jim

    Please guys someone tell me the answer for this question. I guess its a valid question, though I feel that the answer to this question must be quiet easy since somewhere the methods must have been getting implemented.
    Please let me know who does that and how and when!!!
    Hoping for an explanation to this now

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

  • The type must implement the inherited abstract method???

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.ActiveEvent;
    import java.applet.*;
    public class MoveIt extends Applet implements ActionListener
         private Image cup;
         private Panel keyPad;
         public int yaxis = 15;
         public int xaxis = 15;
         private Button keysArray[];
         public void init()
              cup = getImage(getDocumentBase(), "cup.gif");
              Canvas myCanvas = new Canvas();
              setBackground(Color.blue);
              setLayout(new BorderLayout());
              Button up = new Button("Up");
              Button down = new Button("Down");
              Button right = new Button("Right");
              Button left = new Button("Left");
              Button center = new Button("Center");
              add(myCanvas, BorderLayout.NORTH);
              add(keyPad, BorderLayout.SOUTH);
              keyPad.add(up, BorderLayout.NORTH);
              up.addActionListener(this);
              keyPad.add(down, BorderLayout.SOUTH);
              down.addActionListener(this);
              keyPad.add(right, BorderLayout.EAST);
              right.addActionListener(this);
              keyPad.add(left, BorderLayout.WEST);
              left.addActionListener(this);
              keyPad.add(center, BorderLayout.CENTER);
              center.addActionListener(this);
         public void paint( Graphics g )
              g.drawImage( cup, xaxis, yaxis, this );
         public void ActionPerformed(ActionEvent e)
              String action = e.getActionCommand();
              if(action.equals("Up"))
                   yaxis = yaxis - 15;
              if(action.equals("Down"))
                   yaxis = yaxis + 15;
              if(action.equals("Left"))
                   xaxis = xaxis - 15;
              if(action.equals("Right"))
                   xaxis = xaxis + 15;
              if(action.equals("Center"))
                   xaxis = 125;
                   yaxis = 60;
    }How come there is an error:
    The type MoveIt must implement the inherited abstract method
    ActionListener.actionPerformed(ActionEvent)
    What the hell does that mean?

    A class that implements an interface must define the methods of the interface. Your applet (or the one you borrowed) states at the top that it implements the ActionListener interface. If you go to the API, you'll see that this interface declares a method "actionPerformed", and so this class must have a method that matches the one in the interface. I see that your applet will have some Buttons. You'll need an actionPerformed method if you want the buttons to use your class (this) as their action listener.
    Edit: I see that you already have an "ActionPerformed" method, but note that case matters, and this is not the same as "actionPerformed". Change one letter and you're on your way.
    Edited by: Encephalopathic on Jan 15, 2008 8:44 PM

  • About overriding static method inheritance

    I have some class PO2VOPropertyUtilsBean which extends the org.apache.commons.beanutils.PropertyUtilsBean.
    In PropertyUtilsBean,there is a method:
    protected PropertyUtilsBean getInstance() {}I override it in my extend calss PO2VOPropertyUtilsBean:
    protected PO2VOPropertyUtilsBean getInstance() {
          return new PO2VOPropertyUtilsBean();
    }I use Eclipse3.1+Myeclipse4.0,when i choose java5.0 as complier,that all be ok.
    But when i copy the source to my company, my pc uses java1.4 as compiler,it show me errors in the getInstance() method:
    imcompartible return type,it should return PropertyUtilsBean.
    Why?

    Ok, so the getInstance() methods are indeed static.
    As Kaj said, static methods cannot be overridden.
    You would call the method by the classname. For example:
    PropertyUtilsBean bean = PropertyUtilsBean.getInstance();If you write a class PO2VOPropertyUtilsBean with a getInstance() method, the call above will still go to class PropertyUtilsBean, and not to your derived class. After all, how is Java supposed to know that you want to have the method in PO2VOPropertyUtilsBean called? You would need to change the call:
    PropertyUtilsBean bean = PO2VOPropertyUtilsBean.getInstance();

  • Java inherited static operations on static variables

    How does one force a static method in a base class to operate (read/modify) on static variables in the base class and all of its subclasses ?
    From what I've seen, static methods aren't truly inherited; just invoked from the sub-classes within the super's context !! Am I mistaken ?

    It seems I've incorrectly (more like, incompletely) phrased the 1st part of the question to cause a concern in your response. I hate fundamentally flawed approaches as well :-) My title still holds good, though.
    Rephrasing:
    How does one allow a static method defined in a base class, that can already operate (read/modify) on its own static variables, be inheritable in the subclasses, so that they too can use this method to operate on their over-ridden static variables, without the subclasses having to redefine them ?
    Partial Problem Definition:
    Way before any instances of some of the above-discussed classes are created, the classes should be able to fill in a common static variable with data that is unique to the particular class in question. Especially when these so-called static variables are declared final. Therefore, a superclass (in this case the root) can define this method once, and all subclasses would inherit this class method during their class-object initialization and accordingly fill in their 2 cents worth of value in a given static variable - which in this case will have the same name in all the classes involved. This static variable can represent anything - time-of-class-creation, class-level random number etc.,
    An apparently silly example:
    Class A {
    protected static final String canonicalClassName = getMyClassName();
    protected static String getMyClassName() {
    // Implementation
    Class B {
    protected static final String canonicalClassName = getMyClassName();
    What would the commented implementation in getMyClassName() be, so that all subclasses can take advantage of (WITHOUT re-defining) the super's method ?
    Edited by: Matt0000 on Apr 17, 2008 2:21 PM

  • Why java does not force to declare atleast one abstract method

    hi,
    i can define an abstract class without declaring any abstract method in that class. But why wud i do this ? i mean when i have decided that a particular class should be inherited by other subclass and subclass should porvide implementation then there should be atleast one method in the abstract super class which requires implementation.
    All i want to know is why java does not force to declare atleast one abstract method in abstract class.
    there may be some situations where this restriction can create problem if it is like that then can anybody give some example.
    manish

    hi,
    i didn't get u.
    u r trying to say that i have an abstract class with
    only static methods then my questions is why wud
    declare such a class as 'abstract' class? because a
    static method can't be abstract also. Even then if
    somebody want to define such a class with only static
    methods then compiler should force him to declare
    atleast one abstract method which can be implemented
    by subclass, because as i said before if sumbody
    decide to define a class abstract then he wants that
    it should be inhereted but as u r saying a class with
    only static methods then it should not be an abstract
    class it can be a simple class.there's no functional reason, really... actually, factory-like classes are often defined the way Ceci described
    "abstract" only ensures that nobody can ever get an instance of that class (as a matter of fact, what would be the point of getting an instance, if no instance method exists ?)

  • Dynamic call of a static method of an static attribute

    Hi all,
    is it possible to call dynamically a static method of a static attribute of a class.
    The statement without dynamic call would look like this:
    cl_test_class=>static_attribute=>static_method( ).
    I would like to do it like this:
    ('CL_TEST_CLASS')=>static_attribute=>static_method( ).
    Netiher the one nor the other way works for me - I'm getting the error "The notation used is reserved for business object classes".
    Regards, Stefan

    I guess, it is not possible to call method using the short form (parameters in brackets) is not possible in Dynamic Access. You may need to get the attribute first and then call the method.
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: o_same TYPE REF TO lcl_main.
        METHODS: run.
    ENDCLASS.                    "lcl_main DEFINITION
    CLASS lcl_main IMPLEMENTATION.
      METHOD run.
        WRITE: 'success'.
      ENDMETHOD.                    "run
    ENDCLASS.                    "lcl_main IMPLEMENTATION
    START-OF-SELECTION.
      DATA: lo_same TYPE REF TO lcl_main.
      CREATE OBJECT lcl_main=>o_same.
    *  lcl_main=>o_same=>run( ).
      TRY.
          FIELD-SYMBOLS: <fs> TYPE REF TO lcl_main.
          ASSIGN ('LCL_MAIN')=>('O_SAME') TO <fs>.
          CALL METHOD <fs>->('RUN').
        CATCH cx_root.
      ENDTRY.
    Regards,
    Naimesh Patel

Maybe you are looking for