Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a static class derive from an object?

Tags:

c#

oop

I am trying to inherit a non-static class by a static class.

public class foo { }  public static class bar : foo { } 

And I get:

Static class cannot derive from type. Static classes must derive from object.

How can I derive it from object?

The code is in C#.

like image 447
Ali Avatar asked Feb 17 '09 10:02

Ali


People also ask

How do you derive a static class?

The solution couldn't be simpler: public class A { public const string ConstantA = "constant_a"; public const string ConstantB = "constant_b"; // ... } public class B : A { public const string ConstantC = "constant_c"; public const string ConstantD= "constant_d"; // ... }

Can object be created for static class?

A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.

Can a static class inherit from interface?

No, It's not possible to inherit Static class. Static classes are sealed classes so we can't inherit that.

Can we create object of static class in Java?

Remember: In static class, we can easily create objects. The following are major differences between static nested classes and inner classes. A static nested class may be instantiated without instantiating its outer class. Inner classes can access both static and non-static members of the outer class.


2 Answers

There's no value in deriving static classes. The reasons to use inheritance are:

  • Polymorphism
  • Code reuse

You can't get polymorphism with static classes, obviously, because there is no instance to dynamically dispatch on (in other words, it's not like you can pass a Bar to a function expecting a Foo, since you don't have a Bar).

Code reuse is easily solved using composition: give Bar a static instance of Foo.

like image 84
munificent Avatar answered Sep 29 '22 11:09

munificent


From the C# 3.0 specification, section 10.1.1.3:

A static class may not include a class-base specification (§10.1.4) and cannot explicitly specify a base class or a list of implemented interfaces. A static class implicitly inherits from type object.

In other words, you can't do this.

like image 28
Jon Skeet Avatar answered Sep 29 '22 09:09

Jon Skeet