接口(interface)的二三事

话不多说,直接show the code
public class T_interface {
    public static void main(String[] args) {
        //Interface test1 = new Interface(); new 接口时必须实现其抽象实例方法
        Interface test2 = new Interface() {
            @Override
            public int add(int x, int y) {
                return 0;
            }
        };
        Interface test3 = new Test();
        Test test4 = new Test();
        System.out.println(test4.x); // 输出10
        System.out.println(test3.x); // 成功,输出0    成员的调用以声明为就近原则;
        //System.out.println(test3.add(2)); 错误
        System.out.println(Interface.add(2)); // 静态方法只能被类本身调用!静态成员可以被声明为类,实际是其子类的对象所调用。
    }
    interface f{ }  //接口可以为成员类
}
interface Interface {
    //检查是否可以有static成员 √
    static int x = 0;
    //protected int ls();   接口类方法声明都是公开的。公开是因为它们需要被调用和实现吧。
    int add(int x, int y);
    // static int add(int y);    静态方法不可以为抽象方法
//    static int add(int x, int y) {  静态方法与实例方法不可以相同
//        return x + y;
//    }
    //abstract static void add() { }   abstract不能修饰静态方法
   static int add(int y) {
//       x = 1;     接口里的变量都隐式声明为 public static final,而接口里的方法默认情况下访问权限为 public。
       return x + y;
   }
}
class Test implements Interface{
    int x = 10;
    @Override
    public int add(int x, int y) {
        return x + y;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值