简体   繁体   English

Java类扩展了抽象类,但必须具有静态方法

[英]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. 我有一个抽象类Foo(实现OtherThing)和一个扩展Foo的类栏。 I plan on having several other classes that extend Foo and want to make sure they all have Static method. 我计划使用其他几个扩展Foo的类,并希望确保它们都具有Static方法。

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. 我需要任何扩展Foo的类来具有此方法,以便我的Factory可以创建该类。 I can manually add the static method to each class that needs it. 我可以将静态方法手动添加到需要它的每个类中。 Each Bar class will create a slightly different Map. 每个Bar类都会创建一个略有不同的Map。 I tried adding the static method to both the Interface class OtherThing and the Abstract class Foo. 我尝试将静态方法添加到Interface类OtherThing和Abstract类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: 在您的用例中,如果您想从Bar中的Foo调用静态方法,则可以仅在Bar中调用Foo.staticMethod():

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;  
  }  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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