编程语言| java 接口简介

本文探讨了Java中接口的设计目标和实现原理,解释了为何Java不支持多重继承及接口如何模拟这一特性。通过实例说明了接口在声明公共方法头和常量、扩展多个接口的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Interface(Java)

  1. background and design goal
    unlike C++, java doesn’t support multi-inheritance because of its complexity and inefficiency (???)
    all classes in java must have one base class(except for Object), so multi inheritance of classes is not allowed in java, interface can simulate multi-inheritance.
  2. merit and demerit
  3. applicable scene
    a sorting algorithm may expect an object of type Comparable without knowing the specific type
  4. constituent part && key points
    declares only public method headers and public static final constants.
    cannot be instantiated.
    can extend several other interfaces.
    example:
    public interface Recyclable {
    (public) boolean gc(GcMeta gcMeta);
    }
    public interface PeerService extends Recyclable {
    void add(PeerInfo peerInfo);
    PeerInfo get(String cid);
    }
  5. underlying principle
    similar to prototypes
  6. comparision with abstract class
    – class Human extends Animal, Whistler // Error
    – class Human extends Animal implements Whistler // OK
    Unfortunately abstract class has some problems when representing universal properties : extending multi base classes is not allowed in java;
    interface can represent universal properties, simulating multi-inheritance easily.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值