初来乍到,提个问题,如何证明interfac的方法都是public的?求集思广义。

解决方案 »

  1.   

    你也可以在interface的方法前面加上 private,protect,default ,public 试试看会报什么错
      

  2.   

    小弟个人见解,
    interface里面的方法默认都是public static 的
    变量默认都是public final static的。
    刚测试了一下,如果用private修饰interface里面的变量及方法都会报错.代码是:
     interface ts{//定义接口

    //报错private String sk="0";
    //报错private void tests();
    String sk="interface";//修饰符可以不写,或者这样写:
    public static final String test="";
    void test();//修饰符可以不写,也可以这样写:
    public void tests();
    }public class TestTop implements ts {

     
    String sk="s";//注意,这个变量和接口里面的毫无关系,看他们的字体便可知道,
    //被static修饰的会倾斜,而这个地方没有出现倾斜
    //....................................................
    //测试是否是接口里面的方法或者变量的最好一个方法就是,把下面的代码块注释掉,就会报错,这就说明
    //这个方法是接口里面的,必须实现.

    public void test() {
    System.out.println(ts.sk); //这是访问接口里面变量的方式.因为接口里面的变量均被public static final修饰,
    //不能二次赋值,所以在实现的时候,重写接口里面的变量是无效的.但因为它是被static修饰的,故可以通过ts.sk来访问.
    }

    public void tests(){
    System.out.println(ts.sk);
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    TestTop test=new TestTop();
        test.test(); }
    }翻译是有道提供的。。变量:Illegal modifier for the interface field ts.sk; only public, static & final are permitted[非法修改器为该接口场ts sk;只有公共、静态&最终是允许的]方法:Illegal modifier for the interface method tests; only public & abstract are permitted[非法修改器的接口方法测试;只有公共&文摘是允许的
    ]
      

  3.   

    interface只有public abstract或者abstract.public class TT {

    public static void main(String[] args) throws Exception {
    System.out.println(Modifier.toString(AA.class.getModifiers()));
    }
    }interface AA {}
      

  4.   

    定义一个Interface 就是为了让其他类实现 或是其他Interface扩展使用的。
    而Interface中的方法都为抽象方法,也是为了让concrete类重写。
    如果把Interface中的方法定义为非public的,concrete类将看不到Interface中的方法,
    这样做没有任何意义,所以编译器强制Interface 中的方法为public的。
      

  5.   

    <<thinking in java>> 中的习题,现在公布答案 
    public class E03_InterfacePublicMethods
      implements AnInterface {
      // Compile-time error messages for each one
      // of these, stating that you cannot reduce
      // the visibility from the base class' public:
    //!  void f() {}
    //!  void g() {}
    //!  void h() {}
      // Compiles OK:
      public void f() {}
      public void g() {}
      public void h() {}
      public static void main(String args[]) {
        new E03_InterfacePublicMethods();
      }
    } ///:~