tags:

views:

86

answers:

2

I need to define a private abstract class, as I used to do in C#, but this is not possible in Java. How would a Java developer write a construct like below?

public abstract class MyCommand {
    public void execute()
    {
        if (areRequirementsFulfilled())
        {
            executeInternal();
        }
    }
    private abstract void executeInternal();
    private abstract boolean areRequirementsFulfilled();
}

UPDATE:

Forget the question, it is not even possible in C#, I'm a bit dearranged today...

+6  A: 

You can't have private abstract method in java.

When a method is private, the sub classes can't access it, hence they can't Override it.

If you want a similar behavior you'll need protected abstract method.

A compile-time error occurs if a method declaration that contains the keyword abstract also contains any one of the keywords private, static, final, native, strictfp, or synchronized.

And

It would be impossible for a subclass to implement a private abstract method, because private methods are not inherited by subclasses; therefore such a method could never be used.


Resources :

Colin Hebert
Nor in c#......
Kirk Woll
oops, you're right. :-/
elsni
Actually, private methods *can* be accessed by subclasses - as long as those subclasses are enclosed by the super class.
gustafc
@gustafc, even so, if your class is enclosed in the super class you have two choices, either this class is static, then the abstract method isn't accessible (not from a static environment), or the class isn't static but to have one instance of the subclass you need an instance from the super class which isn't instantiable (because it's abstract) nor extendable from outside.
Colin Hebert
+1  A: 

That would be protected instead of private. It means that only classes that extend MyCommand have access to the two methods. (So do all classes from the same package, but that's a minor point.)

Roland Illig