Lecture 14: Interface

本文探讨了Java中接口的概念及其作为抽象数据类型的作用,并详细解释了子类型的关系及其实现方式。此外,还介绍了如何使用静态工厂方法来创建实例,并讨论了泛型接口的应用场景。

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

1 Interface

Java’s interface is a useful language mechanism for expressing an abstract data type (ADT).

1.1 Subtypes

A subtype is simply a subset of the supertype : ArrayList and LinkedList are subtypes of List . “B is a subtype of A” means “every B is an A.” In terms of specifications: “every B satisfies the specification for A.”

How will clients use this ADT as an interface? Here’s an example:

SomeInterface s = new Subtypes(true);
System.out.println("The first character is: " + s.charAt(0));
  • This pattern breaks the abstraction barrier we’ve worked so hard to build between the abstract type and its concrete representations. Clients must know the name of the concrete representation class.
  • Fortunately, (as of Java 8) interfaces are allowed to contain static methods, so we can implement the creator operation valueOf as a static factory method in the interface, as an example:
public interface MyString {

    /** @param b a boolean value
     *  @return string representation of b, either "true" or "false" */
    public static MyString valueOf(boolean b) {
        return new FastMyString(true);
    }

2 Generic Interfaces

public interface Set<E> {
    // ...
  • Generic interface, non-generic implementation.
public class CharSet implements Set<Character>{
//...
  • Generic interface, generic implementation
public class HashSet<E> implements Set<E> {
//...

Reference

[1] 6.005 — Software Construction on MIT OpenCourseWare | OCW 6.005 Homepage at https://ocw.mit.edu/ans7870/6/6.005/s16/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值