Can't declare an abstract method private

前端 未结 6 1561
再見小時候
再見小時候 2020-12-11 00:31

I want to do this, yet I can\'t. Here is my scenario and rational. I have an abstract class for test cases that has an abstract method called test(). The test() method is to

相关标签:
6条回答
  • 2020-12-11 00:59

    abstract means you'll want to define the method in a child class

    private means the child classes won't see the method

    How could it compile ?

    If the method should end up public, declare it public abstract, that's all.

    0 讨论(0)
  • 2020-12-11 01:03

    I want to do this, yet I can't

    Changing this will require rewriting the compiler, which isn't likely.

    You realize why this can never work, right? A subclass can't override a private method, yet, it's abstract which says they must. Catch-22.

    0 讨论(0)
  • 2020-12-11 01:08

    You should declare your "test" method as "protected" to achieve your goal. But it still will be accessible from the package of the class.

    0 讨论(0)
  • 2020-12-11 01:10

    You cannot have a private abstract method because subclasses can't see private members of a superclass. You need to make your test method protected.

    0 讨论(0)
  • 2020-12-11 01:13

    I'd like to point out that it is the choice of Java not to let abstract private methods implemented (e.g. in C++ you can and is advisable). Saying that private methods are not polymorphic in general is just ignorant of the fact that calling and defining a method is two different mechanism - although subclasses can never call a private method of a superclass, they could be able to define it. Mixing the two is a common misconception, please be aware.

    I don't have enough reputation to comment, that's why I'm writing an answer.

    0 讨论(0)
  • 2020-12-11 01:14

    Private methods are not polymorphic (you cannot inherit them), so it makes no sense to make a private method abstract. Making a method abstract means you'd have to override and implement it in a subclass, but since you can't override private methods, you can't make them abstract either.

    You should make it protected instead of private.

    Private really means private to the class you've defined the method in; even subclasses don't see private methods.

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