开发者

interface variables are final and static by default and methods are public and abstract

The question is why it's been decided to have variable as final and static and methods as public and abstract by default.

Is there any particular reason for making them implicit,variable as final and static and methods as public and abstract.

Why they开发者_高级运维 are not allowing static method but allowing static variable?

We have interface to have feature of multiple inheritance in Java and to avoid diamond problem. But how it solves diamond problem,since it does not allow static methods.

In the following program, both interfaces have method with the same name..but while implementing only one we implement...is this how diamond problem is solved?

interface testInt {
    int m = 0;
    void testMethod();
}

interface testInt1 {
    int m = 10;
    void testMethod();
}

public class interfaceCheck implements testInt, testInt1{
        public void testMethod() {
            System . out . println ( "m is"+ testInt.m );   
             System . out . println ( "Hi World!" );    
        }
}


As I see it, an interface declares a set of abilities that implementors must have. It refers to the "what" more than to the "how"; It is more a specification than an implementation guideline.

Therefore, methods which are not public are irrelevant in interfaces. Same with non-static data members, which are more related to the specific implementation.


As far as why they are their defaults - it's just the language specification. They designed it to be that way so it is.

They don't allow static methods in interfaces because interfaces aren't suppose to have any functionality. That's just the definition of an interface.

Java doesn't have a diamond problem since interfaces don't contain code. If your interface was allowed to have code, then Java wouldn't be able to determine whether it should call testInt's testMethod() or testInt1's testMethod(). Since interfaces don't have code, Java knows that there is only 1 implementation of testMethod with code that it needs to run.


I think that non-static variables aren't allowed in interfaces mainly for pragmatic reasons. Multiple inheritance can be more efficient this way and it avoids some ambiguity issues.

As the name suggests, an interface just a definition of the operations available on an instance, therefore, it doesn't contain any method implementation.

For these reasons, it wouldn't make any sense to allow methods not to be public and variables not to be static.

That said, I'm not sure it was a good idea to have different defaults for interfaces than for classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜