2

I have an abstract class, with an abstract member. I want to inherit this member to different classes and make the overrides of the member static.

Something like this:

[<AbstractClass>]
type Parent() = class
  abstract member Att : int
end;;
type Son() = class
  inherit Parent()
  static override Att = 10
end;;
type Daughter() = class
  inherit Parent()
  static override Att = 20
end;;

alternatively

[<AbstractClass>]
type Parent() = class
  static abstract member Att : int
end;;

or

[<AbstractClass>]
type Parent() = class
  abstract static member Att : int
end;;

Then all Sons would have Att=10 and all Daughters would have Att=20. This does not work.

Is there a way to make this work?

Rasmus
  • 23
  • 4
  • Does the solution require that you use static? Or does the solution require that once a Son is created Att=10 and once a Daughter is created Att=20 and then they cannot be changed? e.g. readonly. – Guy Coder Jan 10 '16 at 17:55
  • Readonly actually solves the problem. Thank you very much. – Rasmus Jan 10 '16 at 19:00

1 Answers1

7

This is not possible from the definition of object model - static methods cannot be overriden in C# and any other object language as well.

This is mentioned e.g. here as well (for Java, but this is general to object-oriented programming):

Why cannot we override static method in the derived class

Overriding depends the an instance of a class. Polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for those method defined in the superclass (and overridden in the subclasses). Static methods do not belong to an instance of a class so the concept is not applicable.

Specifically for abstract class, this won't make sense - you either call the method on the derived class (which means it doesn't need to be defined in the superclass), or on the superclass (which means it doesn't need to be abstract), or on an instance (which means it cannot be static).

Community
  • 1
  • 1
Tomas Pastircak
  • 2,867
  • 16
  • 28