tags:

views:

1622

answers:

4

So a abstract class can only be used as a base class which is extended by some other class, right?

So the constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)).

My question is what is the correct one to use between protected and public since the abstract type seems to indicate that technically a public constructor will act very much protected. So should I just use protected on all my constructors?

THANKS!

+2  A: 

If this behavior is true, and I'm not sure it is, you should always use the most restricted scope available for your application to function. So in that case, I would recommend using protected.

IAmCodeMonkey
+5  A: 

since the abstract type seems to indicate that technically a public constructor will act very much protected

This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation will inherit the abstract class' methods and visibility

So the abstract class can certainly have public constructors.

Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:

public class Scratch
{
    public static abstract class A
    {
        public A( int i ) {}
    }

    public static class B extends A
    {
        private B() { super(0); };
    }
}
Jordan Stewart
I believe the modifiers are switched -- with this structure B can't be called from outside Scratch and doesn't support the argument.Swapping them, however, does work, although Intellij's critic complains about access to a private member.
Ken Gentle
My idea was to show that A's constructor is irrelevant to all code outside of its subclasses. It perhaps isn't the best example :)What matters is that the abstract class's constructor can be either protected or public, but it is always called from the subclass so there's no real difference.
Jordan Stewart
A: 

since the abstract type seems to indicate that technically a public constructor will act very much protected

Umm... for abstract classes this constructor scope [public or protected] is not of much difference since the instantiation is not allowed [even if public]. Since it is meant to be invoked by the subclass, it can invoke either public or protected constructor seamlessly.

Its completely on choice what to use. I generally prefer public as it is in most of the cases.

Nrj
A: 

At the very least, an abstract class should have a protected constructor. It's not strictly necessary since it's not possible to use the constructor anyway but it makes the contract explicit.

Another option is to make the constructor private. This is only a good idea though if all of the implementations of the class are private inner classes. A rare but useful example.

JaredPar