28 May 2013

question on static class

How can you make a class which cannot be inherited and instantiated?

If you don't know the answer for this question upfront, you might come up with 3 guess below:

  1. Creating an abstract class:

    Abstract classes cannot be instantiated. It met the first requirement of the question.

  2. Creating a sealed class:

    Sealed classes cannot be inherited. It met the second requirement of the question.

  3. Making the class both abstract and sealed:
       namespace WhenToUseStaticClass
       public abstract static class FormatHelper { }
    When a class marked as abstract and sealed, you will get the below compile time error:

    "an abstract class cannot be sealed or static"

    The above error makes sense.
    1. Why an abstract class cannot be sealed class?

      The reason behind creating an abstract class is that to derive a class from it. But sealed class means it cannot be inherited. Abstract and sealed are contradictory and hence an abstract class cannot be sealed class.

    2. Why an abstract class cannot be the static class?

      Static class members can be used only with class name where as abstract class members cannot accessed outside without a derived class instance. In some way an abstract class and static class are contradictory and hence a class cannot be abstract and static.

As you read, answer 1 & 2 doesn't meet the requirement fully and answer 3 is not possible. Then what is the correct answer to the question?

Make the class as static. Static class cannot be inherited and instantiated