Abstract static methods

Hello,
I've written an abstract class, called AbstractNetworkParticipant. I've also written two sub classes that extend this class. I'm in the process of writing a Viewer class that I'm intending to parameterized with some subclass of AbstractNetworkParticipant,
public class Viewer<T extends AbstractNetworkParticipant> I would like to include a couple of static methods that return Strings for Labeling information to a particular subclass in the Viewer.
So for example, if I have NetworkUser and NetworkAdministrator, both of which extend AbstractNetworkParticipant, I would like to set the text of a JLabel labeling the participant's name to "User Name", or "Administrator Name" depending on the type of participant being viewed.
I would like the method that returns these strings to be static, so that I don't have to have an instance of the current subclass when I initializes the JLabel. An abstract method cannot be static. I attempted to make a non-abstract static method in the abstract class,
  public static getDescriptor() {
     return "Participant";
  }and then override it in each sub class to a more descriptive string (User, or Administrator). However, when I reference the method, it always invokes the method defined in the abstract parent class, rather than in the subclass, whichever it may be.
Can anyone suggest a solution. Should I just forget about the method being static? Is there a better way to implement a solution to this problem?
Thanks
Edited by: paulwooten on Mar 27, 2009 9:58 AM

paulwooten wrote:
The whole point of my original post was in order to learn something about Java that I'm not particularly familiar with. I was having a difficult time articulating the problem precisely, so I tried to draw an analogy between C++ and Java. It turns out I was mistaken in the way C++ works. Fortunately I described my problem adequately enough to both 1. be corrected about how virtual functions actually work in C++, and 2. get advice on how to approach the problem in Java. I never claimed I was a C++ expert, or that I was asking a question about C++. I was just trying to explain my problem as precisely as possible.
I don't mean to disrespect, but your post, and slimy's aren't nearly as constructive as all the other posts that actually addressed my question; either to me personally, or to anyone else who has a similar question and may happen to read this thread. It's not like I dumped a bunch of C++ code here and begged someone to translate it for me. I asked a question, to the best of my ability, several other forum members replied (without giving me a mini lecture on how to learn Java), and now the problem is resolved.Sorry for the confusion. I wasn't complaining about your post. My post wasn't directed at you at all. It's fine to know C++, and to ask how to do something similar in Java. As you said, that wasn't even how you asked your original question. You asked a legitimate question to learn Java, a few people made suggestions, you made a comparison to C++, and people corrected your understanding both of C++ and Java. That's all well and good, and it's a fair way to learn. I see no problem with any of that.
What exactly does "learn Java properly" mean? Read the tutorials and pretend like no other programming languages exist?I was referring to slimy's post where he talked about "knowing C++ properly if you use it as an input to Java". The point of my post was supposed to be that "you can know C++ properly, but +you shouldn't always use that as your input to Java+". A very simple example I've seen of what I meant by "non-proper" Java code, in real [but +bad+ ] Java code at a real company is for String comparison:
String abc = "abc";
String xyz = "xyz";
String another = "xyz";
if (abc.compareTo(xyz) != 0) { // Not "proper" Java
   doSomething();
if (xyz.compareTo(another) == 0) { // Not "proper" Java
   doSomethingElse()
}To me, that looks like someone who copied their C++ knowledge (or, at least, C knowledge) to the extreme. In C, the only function to test equality of two C "strings"--i.e., "null-terminated char arrays" is 'strcmp', and you test equality of the strcmp result to 0 to determine whether two "null-terminated char arrays" represent the same thing:
char abc [] = "abc";
char xyz [] = "xyz";
char another [] = "xyz";
if (strcmp(abc, xyz)) { // could include explicit != 0, but not needed in C
   doSomething();
if (!strcmp(xyz, another)) { // anything non-zero is true in C, so !0 is true
   doSomethingElse();
}"compareTo" sounds like "strcmp", and the comparison to 0 is the same in my above examples.
But, in Java, there is a real "equals" method for Strings, and it should be used:
String abc = "abc";
String xyz = "xyz";
String another = "xyz";
if (!abc.equals(xyz)) { // "proper" Java
   doSomething();
if (xyz.equals(another)) { // "proper" Java
   doSomethingElse()
}I would argue that using "compareTo" to test equality of Strings in Java is "non-proper" Java, and using "equals" to test equality of Strings in Java is "proper" Java. That was my definition of "learning Java properly".
I certainly don't think anyone learning Java needs to pretend that no other programming languages exist--it is fine to know other languages, and to look for the similarities (and differences). However, someone learning Java (or any other language new to them) does need to know that things don't work the same in all languages, so, if they base all of their knowledge by trying to get Java to work exactly the same as C++ (or whatever previous language they knew), their Java will not be "proper" Java. There are often multiple ways to do things "properly" in Java, but copying a C++ program verbatim into Java syntax is not necessarily going to result in the best Java code that you could have. When doing the translation from another language to Java (I realize that isn't your goal, but for some people, that is the goal), you need to be sure that your Java code follows Java rules and standards, and not just assume that the architecture of your Java code should be the same as the architecture of your code in the original language.
I hope that clarifies my intentions. As I said, I wasn't directing my previous comment to you. I think your question and learning approach are absolutely fine.

Similar Messages

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

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

  • Static methods in interfaces

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

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

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

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

  • Abstract class and a static method

    Can i call a static method within an abstract class ?

    public class AbstractDemo {
      public static void main(String[] args) {
        BiPlane biPlane = new BiPlane();
        System.out.println("biplane propulsion = " + biPlane.getPropulsionType());
        JumboJet jumboJet = new JumboJet();
        System.out.println("jet load = " + jumboJet.confirmMaxLoad());
        System.out.println("jet speed = " + jumboJet.getTopSpeed());
        System.out.println(Airplane.confirmMaxLoad());
    abstract class Airplane {
      static String confirmMaxLoad() {
        return "go_get_um, yeehaa!";
      public abstract String getPropulsionType();
      abstract String getTopSpeed();
    class BiPlane extends Airplane {
      public BiPlane() {
        System.out.println("BiPlane constructor");
      static String confirmMaxLoad() {
        return "400 lbs";
      public String getPropulsionType() {
        return "propeller";
      final String getTopSpeed() {
        return "130 knots";
    class JumboJet extends Airplane {
      public JumboJet() {
        System.out.println("JumboJet constructor");
      public String getPropulsionType() {
        return "jet";
      public String getTopSpeed() {
        return "mach .87";
    }

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • 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

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Redefine static method?

    It seems that I cannot redefine a static method in a subclass in ABAP OO, right?
    Is there a reason for that? Is this like this in other languages as well?

    That's true. You cannot redefine static methods in ABAP OO.
    I can add that a class that defines a public or protected static attribute shares this
    attribute with all its subclasses.
    Overriding static methods is possible for example in Java.
    This simple piece of code illustrates this:
    public class Super {
        public static String getNum(){
            return "I'm super";
         public static void main(String[] args) {
             System.out.println("Super: " + Super.getNum());
             System.out.println("Sub: " + Sub.getNum());
    public class Sub extends Super{
        public static String getNum(){
            return "I'm not";
    The output is:
    Super: I'm super
    Sub: I'm not
    When overriding methods in Java you must remember that an instance method cannot override a static method, and a static method cannot hide an instance method.
    In C# a static member can't be marked as 'override', 'virtual' or 'abstract'. But it it is possible to hide a base class static method in a sub-class by using the keyword 'new':
    public class Super
      public static void myMethod()
    public class Sub: Super
      public new static void myMethod()

  • 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

  • Drawbacks of static methods?

    What's the better approach for utility methods:
    a) write abstract class with static methods
    b) write class with non-static methods and instantiate this class to call the public methods.
    ?

    What's the better approach for utility methods:Define "utility methods".
    a) write abstract class with static methodsProbably not - surely a final class would be better than an abstract one?
    b) write class with non-static methods and instantiate
    this class to call the public methods.Do you (or might you ever) want to be able to plug in different implementations? If so, then this is the better option. If not, then a final class with all methods static will probably do the job very well.

  • No warning for 'name clash' of static methods

    The background is that I am trying to design a package which allows conversion methods to be 'plugged-in' to a class within a class hierarchy so that users can choose how objects are converted to double values. (For example, a 'city-block' conversion might be used instead of the Euclidean-distance one for class TwoD below.) I am trying to use generics to ensure that only converters specific to the appropriate class can be 'plugged-in' and also to simplify the definition of new converters.
    The issue that has arisen is a case which is not 'type-safe', in that the behaviour is not what I would expect from the type specifications, yet no warning is given. The full code is below.
    public abstract class Base {
        public abstract Converter getConverter();
        public double convert() {
            return this.getConverter().convert(this); // produces a warning
    public class OneD extends Base {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter getConverter() {
            return converter;
    public class TwoD extends OneD {
        static Converter<TwoD> converter;
        int y;
        public TwoD(int x, int y) {
            super(x);
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        }                                   // compiles OK with no warning
        public Converter getConverter() {
            return converter;
    public abstract class Converter<T> {
        public abstract double convert(T val);
    public class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    public class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    public class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());
              // wrong type of converter; should not be allowed
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }This produces the output:
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.4142135623730951
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.0The first line of this shows that the all is working OK, but in the second line we see that the wrong type of converter has been plugged-in to class TwoD, with no complaints or warnings at compile or run-time. I understand why this is so (as a result of erasure), but I am surprised that no warning is given that the static method setConverter() in class TwoD clashes with the one in OneD. Is this really type-safe behaviour? (If the two methods are made instance methods instead of static, the code does not compile because of a 'name clash' error.)
    Incidentally, an 'unchecked warning' arises because of the use of the raw class Converter in class Base, but I cannot figure out how to avoid this. The warning is right, and signals that we cannot be sure that the converter is the appropriate type for the argument. It is up to subclasses to ensure this and I cannot figure out how to guarantee that it will be so.

    public abstract class Base {
    public abstract Converter getConverter();
    public double convert() {
    return this.getConverter().convert(this); // produces a warning
    }Some of the problems you're seeing can be resolved
    by organizing your code better:
    abstract class Base<T extends Base<T>> {
        public abstract Converter<T> getConverter();
        public double convert() {
            return this.getConverter().convert(getThis());
        abstract protected T getThis();
    class OneD extends Base<OneD> {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter<OneD> getConverter() {
            return converter;
        protected OneD getThis() { return this; }
    class TwoD extends Base<TwoD> {
        static Converter<TwoD> converter;
        int y;
        int x;
        public TwoD(int x, int y) {
            this.x = x;
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        public Converter<TwoD> getConverter() {
            return converter;
        protected TwoD getThis() { return this; }
    abstract class Converter<T> {
        public abstract double convert(T val);
    class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());  // error
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }

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

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

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

Maybe you are looking for