Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force abstract class childs to implement a static method? [duplicate]

Tags:

c#

oop

Possible Duplicate:
How can I force inheriting classes to implement a static method in C#?

I understand abstract and static are opposite, but I want to force derived classes to implement a static method. how can I do that?

Edit after SimonC : While trying to describe what I want to do, i realized that static methods of super class will not be able to call the overridden subclass version.

But olivier's alternative solution looks nice.

like image 554
bokan Avatar asked Nov 26 '12 14:11

bokan


People also ask

Can we override static method in abstract class?

If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.

Can we have static method with same name in both parent and child class?

The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters.

How can we create static method in abstract class?

You cannot create an abstract static method. What you can create is non abstract static method. Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality. Save this answer.

Can child class inherit static method?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.


1 Answers

A possible approach of combining a static behavior with inheritance or interface implementation is to use the singleton pattern. The access to a singleton object is static, but the object is created with new like a "normal" object

public interface ISomeInterface { ... }

public class SomeClass : ISomeInterface
{ 
    public static readonly SomeClass Instance = new SomeClass();

    private SomeClass()
    { 
    }

    // TODO: Implement ISomeInterface
    // and/or override members from a base class.
}

Accessing a method of the singleton

ISomeInterface obj = SomeClass.Instance; // Static access to interface.
var y = obj.SomeMethod(x);
like image 98
Olivier Jacot-Descombes Avatar answered Oct 07 '22 01:10

Olivier Jacot-Descombes