interface methods

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85388618

Interface knowledge:

You can choose to explicitly declare the methods in an interface as public, but they are public even if you don’t say it. So when you implement an interface , the methods from the interface must be defined as public . Otherwise, they would default to package access, and you’d be reducing the accessibility of a method during inheritance, which is not allowed by the Java compiler.

for example:

// interfaces/ImplementingAnInterface.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface Concept { // Package access
  void idea1();

  void idea2();

  // protected void idea3(); // [1]
}

class Implementation implements Concept {
  public void idea1() {
    System.out.println("idea1");
  }

  public void idea2() {
    System.out.println("idea2");
  }
}

when [1] is uncommented, the compile error is: 

$ javac interfaces/ImplementingAnInterface.java
interfaces/ImplementingAnInterface.java:11: error: modifier protected not allowed here
  protected void idea3(); // [1]
                 ^
interfaces/ImplementingAnInterface.java:14: error: Implementation is not abstract and does not override abstract method ide
a3() in Concept
class Implementation implements Concept {
^
2 errors

referecnes:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/interfaces/ImplementingAnInterface.java

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/85388618