Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

derived class accessibility

Tags:

java

c#

.net

Why in C# it is not allowed for derived classes to have greater accessibility than its base class.

For example this will give error : Inconsistent accessibility: base class 'BaseClass' is less accessible than class 'DerivedClass'

internal class BaseClass
{
}

public class DerivedClass : BaseClass
{
}

And why it is allowed in Java.

like image 751
NDeveloper Avatar asked May 18 '11 10:05

NDeveloper


1 Answers

UPDATE: This question was the subject of my blog on November 13th 2012. Thanks for the great question!

Why in C# it is not allowed for derived classes to have greater accessibility than its base class?

In addition to the other good answers, consider this scenario. You and your coworker Alice are working on different parts of the same assembly. Alice writes a class:

public class ComplicatedClass
{
    public void DoDangerousThing() { ... }
}

You then write

public class EvenMoreComplicatedClass : ComplicatedClass
{
}

Great. Now Alice gets a security review from Bob, and they realize that (1) no customer ever needs to use ComplicatedClass, and (2) DoDangerousThing exposes a security hole that hostile code could take advantage of. Internal code of course does not.

So Alice changes her code to

internal class ComplicatedClass
{
    public void DoDangerousThing() { ... }
}

Figuring there is no need to change "public" to "internal" on the method because of course public means "public to things that can see this class", and now no external code can see this class.

What should happen to your code when Alice recompiles with this change? It should fail to compile. You have made an assumption that users need to see the base class, and Alice has made a change that violates that assumption. The safe thing to do is for the compiler to tell Alice that she needs to come talk to you so that you can resolve this problem without exposing the customer to the vulnerability of DoDangerousThing.

Why it is allowed in Java?

No idea, sorry.

like image 108
Eric Lippert Avatar answered Oct 29 '22 22:10

Eric Lippert