接口interface

接口可以有变量,不过这些变量都是static并且是final类型的。
在interface里面的方法,默认都是public的,而且必须是public,不能加上除了public以外的访问权限,因此当其他类implements这个interface时,如果降低了访问权限,那么编译器会报错。
例子:

interface Instrument{
        void play();
}

class Piano implements Instrument{
        void play(){
                System.out.println("play piano");
        }
}

编译会报错:

test.java:6: error: play() in Piano cannot implement play() in Instrument
        void play(){
             ^
  attempting to assign weaker access privileges; was public
1 error

猜你喜欢

转载自blog.csdn.net/whoami_I/article/details/83104677