what is the implicit declaration of interface methods in Java 8?

浪子不回头ぞ 提交于 2019-12-11 04:04:26

问题


I was reading my old SCJP 6 book(author Kathy Sierra,Bert Bates) mentioned

  • All the interface methods are implicitly public and abstract by default
  • interface methods must not be static

For example, if we declare

interface Car
{
    void bounce();               //no need of public abstract
    void setBounceFactor(int b); //no need of public abstract
}  

What the compiler sees

interface Car
{
    public abstract void bounce();
    public abstract void setBounceFactor(int b);
}   

But from Java 8, interfaces can now define static methods. see this article everything-about-java-8
My question, what is the implicit declaration of interface methods in Java 8? Only public or nothing?


回答1:


The rules for implicit modifiers do not change. Implicit modifiers are used when no other modifiers are specified. abstract is implied when neither static nor default has been specified. And all methods are always public whether implicit or explicit. Note that interface fields were always implicitly public static. This doesn’t change too.

But for the final words we should wait for the completion of Java 8.




回答2:


Afaik it is something you can add and is added without changes to implementing classes.

For example. The List class will have a sort() method added. A sub class could have this method already but if every class needed this method it would break a lot of code and make having a default a bit useless.

I believe it is expected that the default method will be simple and call a static method or helper class to leave the interface uncluttered.

in short, default methods are public but not abstract.

btw interfaces have a method for static field initialisation.




回答3:


what is the implicit declaration of interface methods in Java 8? Only public or nothing?

Answer is: It is still public. private or protected are restricted. Look at following two examples

public interface A {

    static void foo() {// Its ok. public will implicitly call.
        System.out.println("A.foo");
    } 
   private static void foo2() {// Compile time error
        System.out.println("A.foo2");
    }
}


来源:https://stackoverflow.com/questions/20045759/what-is-the-implicit-declaration-of-interface-methods-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!