All I want to do is make sure that child classes of the class Item implement a static method and I want this to be checked at compile time to avoid runtime errors.
abstract classes with static methods don't seem to work:
ERROR: A static member cannot be marked as override, virtual, or abstract
public abstract class Item
{
public static abstract Item GetHistoricalItem(int id, DateTime pastDateTime);
}
public class Customer : Item
{
public static override Customer GetHistoricalItem(int id, DateTime pastDateTime)
{
return new Customer();
}
}
public class Address : Item
{
public static override Address GetHistoricalItem(int id, DateTime pastDateTime)
{
return new Address();
}
}
and interfaces don't seem to work either:
ERROR: Customer does not implement interface member GetHistoricalItem()
public class Customer : Item, HistoricalItem
{
public static Customer GetHistoricalItem(int id, DateTime pastDateTime)
{
return new Customer();
}
}
public class Address : Item, HistoricalItem
{
public static Address GetHistoricalItem(int id, DateTime pastDateTime)
{
return new Address();
}
}
interface HistoricalItem
{
Item GetHistoricalItem();
}
Is there some workaround for this to have the compiler check if inheriting classes implement a static method with a certain signature or not?
A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.
Static method can be inherited similar to normal methods, however unlike normal methods it is impossible to create "abstract" methods in order to force static method overriding.
Quick A: Yes, and there are no ambiguity with static members.
Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.
There is a workaround i figured out for your scenario:
public class Customer : Reference<Customer>, IHistoricalItem
{
}
public class Address : Reference<Address>, IHistoricalItem
{
}
public interface IHistoricalItem
{
}
public class Reference<T> where T : IHistoricalItem, new()
{
public static T GetHistoricItem(int id, DateTime pastDateTime)
{
return new T();
}
}
Hope this helps!!
This cannout be done.
Have a look at Why can’t I have abstract static methods in c#?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With