Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class declaring a protected member

I'm reading the book "C# Language", and hit this note from Vladimir Reshetnikov:

If a static class declares a protected or protected internal member, a compile-time error occurs (CS1057).

May I know why? What's wrong with a static class having a protected member? Static class can have private member so I guess this CS1057 error is not due to accessibility, but maybe it's due to come compilation issue? as protected member could be overridden in child classes... but I couldn't figure out why.

like image 812
athos Avatar asked Jul 02 '11 16:07

athos


People also ask

Can static class contain protected members?

Since Static classes are sealed classes, and sealed classes can not be inherited,hence it can not contain protected members, because protected members can not be inherited.

Can we use static or protected for constructor?

One of the important property of java constructor is that it can not be static. We know static keyword belongs to a class rather than the object of a class. A constructor is called when an object of a class is created, so no use of the static constructor.

Can static method be protected in C++?

Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

Can static method be protected in Java?

Core Java bootcamp program with Hands on practiceYes, we can have private methods or private static methods in an interface in Java 9.


2 Answers

Because you can't inherit a static class, protected serves no purpose - only public and private make sense here.

More details can be found here: Why can't I inherit static classes?

like image 64
Shadow Wizard Hates Omicron Avatar answered Oct 27 '22 02:10

Shadow Wizard Hates Omicron


Protected members means they can be accessed from child/derived classes. But the main features of static class are:

  1. Only contain static members;

  2. Can't be instantiated;

  3. Are sealed.

That's why static classes can't have protected members.

like image 43
Rahul Avatar answered Oct 27 '22 03:10

Rahul