Whimusical
Whimusical

Reputation: 6629

How to force private visibility to child's method on an abstract class abstract method?

I would like to force my abstract class children to implement my abstract method as private. Is that possible?

Upvotes: 0

Views: 441

Answers (2)

Dima Maligin
Dima Maligin

Reputation: 1482

First @Ravinder Reddy's answer is absolutely right and you should NOT use my example without accepting my terms and conditions which basically state("Use at your own risk").

I can't say its pretty or useful but I assume you can do something like:

public abstract class Master {}

public abstract class Super extends Master{
    protected abstract void foo();
}

public class Sub extends Master {

    private Inner inner = new Inner();

    private void foo() {
        inner.foo();
    }

    private class Inner extends Super {
        @Override
        protected void foo() {
            System.out.println("foo");
        }
    }

}

PS: I don't think it is useful in any way(I'm not even sure this will work).

Upvotes: 2

Pandiri
Pandiri

Reputation: 329

The visibility of an overriding method can not be less than that of overriden method. That is to say, you can't override a public method and make it protected OR private.

since abstract methods are either protected OR public apart from default (since they are supposed to be overriden by sub-classes), the implementation of the method can not be private.

Upvotes: 3

Related Questions