I faced with a sample code in Java and it brought me a question.
Java sample code is:
...
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) throws IOException {
CLibrary.INSTANCE.printf("Hello, World\n");
}
But in C# we cannot write like that:
public interface IMyInterface {
static readonly int staticInt = 5; // compile error
static readonly SomeClass staticInstance = new SomeClass(); // compile error
}
What is the difference between these two languages/frameworks?
What design policy permit java to have const fields in an interface or what prevents .NET from having that?
This is because it's not allowed in java, since Object is the base class for all the classes and we can't have one class level static method and another instance method with same signature.
By default all the members of Interface are public and abstract. The interface will always defined with the help of keyword 'interface'. Interface cannot contain fields because they represent a particular implementation of data. Multiple inheritance is possible with the help of Interfaces but not with classes.
Static methods in an interface since java8Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
Similar to Default Method in Interface, the static method in an interface can be defined in the interface, but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only.
The use of interfaces to hold constants is usually frowned on these days in Java too. (I'd say that storing non-compile-time-constant fields like your example is even more frowned upon.)
Fundamentally, it's at odd with the idea of an interface: a contract that the implementation will uphold. The implementation isn't going to provide the field, so what's it doing there?
I suspect the C# team decided that it was sufficiently at odds with the concept behind interfaces to not include it in the language. I don't know whether it's just a C# restriction or a CLR restriction too. For example, I know that the CLR allows interfaces to declare nested types, but C# doesn't currently allow this.
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