Interfaces

阅读Java的官方Doc,总结如下。

What is Interface

An interface is a reference type, similar to a class, that can contain only

  1. constants (implicitly public, static, final)
  2. method signatures (no method body, no braces)
  3. default methods (has method body)
  4. static methods (has method body)
  5. nested types

Keypoints

Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

A class can implement multi interfaces.

An interface can extend multi interface.

All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

Default Methods

A pretty clear application scenario here.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

When you extend an interface that contains a default method, you can do the following:

  1. Not mention the default method at all, which lets your extended interface inherit the default method.
  2. Redeclare the default method, which makes it abstract.
  3. Redefine the default method, which overrides it.

Special Case

Look at following codes. ContentVisitor is an interface.

private final ContentVisitor visitor = new ContentVisitor() {
    public void onStartDocument() {
        throw new IllegalStateException();
    }

Did we create an instance of interface?

No. We can't instantiate an interface. Actually, what these codes do is to define an anonymous class that implements the interface, and instantiate that class.

It's the same with following codes.

private final class AnonymousContentVisitor implements ContentVisitor {
    public void onStartDocument() {
        throw new IllegalStateException();
    }
}

private final ContentVisitor visitor = new AnonymousContentVisitor();

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4949626.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值