Class protected and public

4

What is the behavior of a protected class?

What is the impact of access modifiers (especially private and protected) on classes, and what are their common uses?

I can understand its functionality when attributed to methods, properties and attributes, but I can not see the same when it comes to a class or interface.

    
asked by anonymous 03.06.2014 / 15:50

1 answer

5

A top-level class (defined directly in the namespace) can not be protected - is a compilation error. You can only define protected classes if they are defined within other classes (such as nested classes ). What the modifier does is that only the class itself within which its nested class is defined, or its subclasses, can access its protected class.

For example:

protected class A { } // não compila - erro

public class B {
    protected class C { }
    private void Metodo1() {
        // Funciona
        var c = new C();
        Console.WriteLine(c);
    }
}

public class D {
    private void Metodo2() {
        var c = new C(); // não compila - erro
        Console.WriteLine(c);
    }
}

public class E : B {
    private void Metodo3() {
        // Funciona
        var c = new B.C();
        Console.WriteLine(c);
    }
}
    
03.06.2014 / 15:57