How to force a method to be overridden in java?

后端 未结 5 2177
忘掉有多难
忘掉有多难 2020-12-15 02:36

I have to create a lot of very similar classes which have just one method different between them. So I figured creating abstract class would be a good way to achieve this. B

相关标签:
5条回答
  • 2020-12-15 03:02

    You need an abstract method on your base class:

    public abstract class BaseClass {
        public abstract void foo();
    }
    

    This way, you don't specify a default behavior and you force non-abstract classes inheriting from BaseClass to specify an implementation for foo.

    0 讨论(0)
  • 2020-12-15 03:02

    If you have an abstract class, then make your method (let's say foo abstract as well)

    public abstract void foo();
    

    Then all subclasses will have to override foo.

    0 讨论(0)
  • 2020-12-15 03:12

    Make this method abstract.

    0 讨论(0)
  • 2020-12-15 03:16

    Just make the method abstract.

    This will force all subclasses to implement it, even if it is implemented in a super class of the abstract class.

    public abstract void foo();
    
    0 讨论(0)
  • 2020-12-15 03:21

    Just define foo() as an abstract method in the base class:

    public abstract class Bar {
       abstract void foo();
    }
    

    See The Java™ Tutorials (Interfaces and Inheritance) for more information.

    0 讨论(0)
提交回复
热议问题