Relevance of 'public' constructor in abstr

2019-04-18 14:02发布

Is there any relevance of a 'public' constructor in an abstract class? I can not think of any possible way to use it, in that case shouldn't it be treated as error by compiler (C#, not sure if other languages allow that).

Sample Code:

internal abstract class Vehicle
{
    public Vehicle()
    {            
    }
}

The C# compiler allows this code to compile, while there is no way i can call this contructor from the outside world. It can be called from derived classes only. So shouldn't it allow 'protected' and 'private' modifiers only. Please comment.

4条回答
Evening l夕情丶
2楼-- · 2019-04-18 14:28

Dupe: there is another question on SO just like this: Abstract class constructor access modifier

The answers on that question come down to the same thing in the end: it does not really matter if you declare it protected or public.

Also there seems to be some discussion about it in literature (e.g. in Framework Design Guidelines). This is referenced in this blogpost: Good design or bad design of abstract class?

查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-18 14:41

There's no reason for a public constructor for an abstract class. I'd assume that the reason that the compiler doesn't complain is as simple that they just didn't spend time covering that since it really doesn't matter if it's public or protected.

查看更多
We Are One
4楼-- · 2019-04-18 14:45

Yes, a public ctor on an abstract class is meaningless and a bit misleading as it will behave as protected in that only derived classes may call it.

A private ctor will have little meaning outside of interesting edge cases.

A protected ctor would make sense if required by derived classes.

查看更多
一纸荒年 Trace。
5楼-- · 2019-04-18 14:54

Inside an abstract class, for an instance constructor, modifiers public, protected internal, and protected are all equivalent. Then internal is more strict than them, and private is the most strict access.

If all instance constructors are private, only classes nested inside the class in question can inherit from it.

Note: If no instance constructors are given for a non-static class, then the compiler will generate one by itself. That's a constructor taking zero arguments. If the class is abstract, that auto-generated constructor is protected. Otherwise it is public.

The only situation I can think of where it makes a difference if an instance constructor of an abstract class is public or protected, is when you use reflection. As an example, saying

ConstructorInfo[] ctors = typeof(Vehicle).GetConstructors();

will give an empty array if the sole constructor is protected, and a length-1 array if it's public. But of course there are overloads that specify BindingFlags, so this is not a problem, just something to remember if one uses reflection.

查看更多
登录 后发表回答