简体   繁体   中英

Java Class extends Abstract class but must have static method

I'm just playing around creating a program. I have an Abstract Class Foo (implements OtherThing), and a Class Bar that extends Foo. I plan on having several other classes that extend Foo and want to make sure they all have Static method.

public abstract class Foo implements OtherThing {//....}  

public class Bar extends Foo{  
  public static Map<Enum, List<AnotherEnum> getSomeThingMap(){  
    create someThingMap;  
    someThingMap.put(Enum, List<AnotherEnum>);
    return someThingMap;  
  }  
}  

I need any class that extends Foo to have this method in order for my Factory that creates the class to work. I can manually add the static method to each class that needs it. Each Bar class will create a slightly different Map. I tried adding the static method to both the Interface class OtherThing and the Abstract class Foo. Any way to do this or am I stuck adding this method to each class that I need to. I know it's not really hard just would prefer to force this method to be there.

I think there is no way to inherit static Methods. But it should not be necessary, because you can call the static method from your top level class directly, just make sure they are public.

Just to remember: Static Methods of a Class should not be used to model Object behavior, valid Use Cases for a static method are in general routines that do not manipulate the state of the underlying object. If you are not familiar with object-oriented design, it would be worth having a look, to make your code more maintainable.

I your use case if you want to call a static method from Foo in Bar you can just call Foo.staticMethod() in Bar:

public abstract class Foo implements OtherThing {//....}  

public class Bar extends Foo{  
  public static Map<Enum, List<AnotherEnum> getSomeThingMap(){  
    create someThingMap; 

    //Call your static Method from Foo here
    Foo.staticMethod()
    someThingMap.put(Enum, List<AnotherEnum>);
    return someThingMap;  
  }  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM