Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java permit interfaces to have static readonly fields while .NET interfaces cannot?

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?

like image 747
mjalil Avatar asked Aug 01 '10 06:08

mjalil


People also ask

Why static method is not allowed in interface?

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.

Why Interfaces Cannot have fields?

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.

CAN interface in Java have static methods in it?

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.

Can we put a static method in Interfaces?

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.


1 Answers

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.

like image 148
Jon Skeet Avatar answered Oct 22 '22 17:10

Jon Skeet