【问题标题】:Is there any way to implement 'abstract class method' in java? [duplicate]有没有办法在java中实现“抽象类方法”? [复制]
【发布时间】:2014-11-24 18:46:54
【问题描述】:

更新: 我知道静态方法不可能是抽象的,而且我知道为什么,这不是一个像“它是否可能?”这样的问题。或“为什么不可能?”,我只是想知道是否有任何方法可以得到我想要的。

好吧,如果您听说过 python 中的@classmethod,则可以跳过其余部分。

这就是我想要的:在某些情况下,某些方法只是函数,我只需要它的功能。但是,在 Java 中,您必须将所有内容放在一个类中,因此我必须将这些 函数 包装在一个类中并将它们设置为静态。问题是,对于像这样的类,我不需要,我也不应该需要它的任何实例。同时,我想要这样的类的层次结构。这里的层次结构就像一些“控制”:我可以控制你应该做什么的子类,也就是你应该拥有什么方法/功能。


众所周知,我们不能在类中声明static abstract 方法。

但是,在某些情况下,您只需要方法而不是实例,并且您需要方法是抽象的并在子类中实现。

有人指出this may be a poor design in java,但是有什么可能的解决方案吗?

【问题讨论】:

  • 你想用它做什么?
  • 没有。将 static 方法标记为 abstract 是没有意义的。方法的覆盖基于对象(实例),而不是类型本身。静态方法仅依赖于类型,而不依赖于任何特定实例。为什么不直接拨打MyabstractClass.someMethod()
  • 您现在无法创建 abstract class 的实例,所以我现在确定您希望添加 static 会做不同的事情,或者您尝试做不同的事情。
  • 顺便说一句,如果您只想要抽象方法,接口可能是更好的选择。
  • 这对我来说似乎是一个 XY 问题。你到底想做什么?

标签: java


【解决方案1】:

不,你不能
主要是因为“抽象”和“静态”方法的术语相互矛盾。 请参阅此处的详细说明: Why can't static methods be abstract in Java

【讨论】:

    【解决方案2】:

    您的静态方法不能是抽象的,但您可以使用函数式接口,预定义的接口,如 FunctionBiFunction 甚至 Consumer 很可能满足您的所有需求,这是预定义接口的列表:@987654324 @

    如果这些不符合您的要求,您可以 write your own interfaces 并因此能够传递任意方法引用......但请务必始终检查 null

    【讨论】:

      【解决方案3】:

      静态方法不能声明为抽象的,因为覆盖(子类型多态性)不适用于静态方法。如果您需要解决方法,这里有一个:

      public void myMainFunction() {
          ArrayList<Animal> animals = new ArrayList<Animal>();
          animals.add(AnimalFactory.createAnimal(Bird.class,birdXML));
          animals.add(AnimalFactory.createAnimal(Dog.class,dogXML));
      }
      
      public abstract class Animal {
          /**
           * Every animal subclass must be able to be created from XML when required
           * (E.g. if there is a tag <bird></bird>, bird would call its 'createFromXML' method
           */
          public abstract Animal createFromXML(String XML);
      }
      
      public class Bird extends Animal {
          @Override
          public Bird createFromXML(String XML) {
          // Implementation of how a bird is created with XML
          }
      } 
      
      public class Dog extends Animal {
          @Override
          public Dog createFromXML(String XML) {
          // Implementation of how a dog is created with XML
          }
      }
      
      public class AnimalFactory{
          public static <T extends Animal> Animal createAnimal(Class<T> animalClass, String xml) {
            // Here check class and create instance appropriately and call createFromXml
            // and return the cat or dog
          }
      }
      

      我从这里得到它:Static abstract method workaround

      【讨论】:

        猜你喜欢
        • 2011-12-01
        • 1970-01-01
        • 2023-03-10
        • 2014-06-30
        • 2022-11-20
        • 2015-04-11
        • 1970-01-01
        • 2011-07-10
        相关资源
        最近更新 更多