《On Java 中文版 基础卷》阅读笔记 接口 19

《On Java 中文版 基础卷》阅读笔记 接口 19

10.5 组合多个接口

因为接口根本没有实现,也就是说,没有与接口关联的存储,所以也就没有什么可以阻止多个接口组合在一起​。

这是很有用的,因为有时你想说,​"一个 x 是一个 a,同时也是一个 b 和一个 c"​。

在一个子类里,Java 并没有强制要求其基类是抽象的或具体的(即没有抽象方法)​。

如果确实是从非接口里继承,则只能继承一个。其余的所有基元素 (base element) 都必须是接口。

将所有的接口名称放在 implements 关键字后面,并用逗号分隔它们,你可以拥有任意数量的接口。

可以向上转型到每个接口,因为每个接口都是一个独立的类型。

下面的示例显示了将一个具体类与几个接口相结合来生成一个新类:

java 复制代码
package interfaces;
// interfaces/Adventure.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Multiple interfaces

interface CanFight {
  void fight();
}

interface CanSwim {
  void swim();
}

interface CanFly {
  void fly();
}

class ActionCharacter {
  public void fight() {}
}

class Hero extends ActionCharacter
    implements CanFight, CanSwim, CanFly {
  @Override public void swim() {}
  @Override public void fly() {}
}

public class Adventure {
  public static void t(CanFight x) { x.fight(); }
  public static void u(CanSwim x) { x.swim(); }
  public static void v(CanFly x) { x.fly(); }
  public static void w(ActionCharacter x) { x.fight(); }
  public static void main(String[] args) {
    Hero h = new Hero();
    t(h); // Treat it as a CanFight
    u(h); // Treat it as a CanSwim
    v(h); // Treat it as a CanFly
    w(h); // Treat it as an ActionCharacter
  }
}

Hero 将具体类 ActionCharacter 与接口 CanFight、CanSwim 和 CanFly 结合在一起。

当以这种方式将具体类与接口结合时,具体类必须在前面,然后才是接口(否则编译器会报错)​。

fight() 的签名在接口 CanFight 和类 ActionCharacter 中是相同的,并且在 Hero 中没有提供 fight() 的定义。

你可以扩展一个接口,但是你的接口并非只有一个。

当创建一个对象时,所有的定义必须都已经存在。

尽管 Hero 没有明确提供 fight() 的定义,但继承的 ActionCharacter 提供了。

因此,我们可以创建 Hero 对象。

Adventure 提供了四个方法,它们的参数类型是各种接口和具体类。

当创建一个 Hero 对象时,它可以被传递给这些方法中的任何一个,这意味着它会依次向上转型到每个接口。

由于 Java 接口的设计方式,这些方法无须程序员做任何特别处理就能正常工作。

请记住,前面的示例揭示了使用接口的核心原因之一:向上转型为多个基类型(以及这样做所提供的灵活性)​。

但是,使用接口的第二个原因与使用抽象基类相同:防止客户程序员创建此类的对象,并明确这只是一个接口。

这就带来了一个问题:应该使用接口还是抽象类?

如果可以在没有任何方法定义或成员变量的情况下创建基类,那么就使用接口而非抽象类。

事实上,如果你认为某个类可以作为基类的话,也就可以考虑把它设计成接口(在10.11节中会重新讨论这个主题)​。

10.6 通过继承来扩展接口

可以使用继承轻松地向接口里添加新的方法声明,也可以通过继承将多个接口组合成一个新接口。

在这两种情况下,都会获得一个新接口,如下例所示:

java 复制代码
package interfaces;
// interfaces/HorrorShow.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Extending an interface with inheritance

interface Monster {
  void menace();
}

interface DangerousMonster extends Monster {
  void destroy();
}

interface Lethal {
  void kill();
}

class DragonZilla implements DangerousMonster {
  @Override public void menace() {}
  @Override public void destroy() {}
}

interface Vampire extends DangerousMonster, Lethal {
  void drinkBlood();
}

class VeryBadVampire implements Vampire {
  @Override public void menace() {}
  @Override public void destroy() {}
  @Override public void kill() {}
  @Override public void drinkBlood() {}
}

public class HorrorShow {
  static void u(Monster b) { b.menace(); }
  static void v(DangerousMonster d) {
    d.menace();
    d.destroy();
  }
  static void w(Lethal l) { l.kill(); }
  public static void main(String[] args) {
    DangerousMonster barney = new DragonZilla();
    u(barney);
    v(barney);
    Vampire vlad = new VeryBadVampire();
    u(vlad);
    v(vlad);
    w(vlad);
  }
}

DangerousMonster 是对 Monster 简单扩展后产生的一个新接口。DragonZilla 实现了它。

Vampire 中使用的语法仅在继承接口时有效。

通常,只能将 extends 用于单个类,但是在构建新接口时,extends 可以关联多个父接口 (base interface)。注意接口名称用逗号分隔。

组合接口时的名称冲突

实现多个接口时有一个小陷阱。在前面的例子中,CanFight 和 ActionCharacter 都有一个完全相同的 void Fight() 方法。

完全相同的方法不是问题,但如果方法的签名或返回类型不同呢?下面是一个示例:

java 复制代码
package interfaces;
// interfaces/InterfaceCollision.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface I1 { void f(); }
interface I2 { int f(int i); }
interface I3 { int f(); }
class C { public int f() { return 1; } }

class C2 implements I1, I2 {
  @Override
  public void f() {}
  @Override
  public int f(int i) { return 1; } // Overloaded
}

class C3 extends C implements I2 {
  @Override
  public int f(int i) { return 1; } // Overloaded
}

class C4 extends C implements I3 {
  // Identical, no problem:
  @Override public int f() { return 1; }
}

// Methods differ only by return type:
//- class C5 extends C implements I1 {}
//- interface I4 extends I1, I3 {}

之所以出现问题,是因为重写、实现和重载令人不快地混合在一起。

此外,重载方法不能只有返回类型不同。

当最后两行取消注释时,错误消息说明了一切:

将接口组合在一起时,在不同接口中使用相同的方法名称通常会导致代码可读性较差。应该努力避免这种情况。

10.7 适配接口

引入接口最令人信服的原因之一是,可以允许同一接口有多个实现。

在简单的情况下,它的体现形式可以是一个接受接口的方法,调用者实现该接口并将其对象传递给该方法。

因此,接口的一个常见用途就是前面提到的策略设计模式。

你编写一个执行某些操作的方法,该方法接受指定的接口作为参数。

你基本上是在表示 "可以用这个方法来操作任何对象,只要这个对象遵循我的接口"​。

这使你的方法更加灵活、通用,并且可复用性也更高。

例如,Scanner 类的构造器(在第 18 章会介绍更多信息)接受一个 Readable 接口作为参数。

你会发现 Readable 不是 Java 标准库中任何其他方法的参数,它是专门为 Scanner 创建的,因此 Scanner 就不用将其参数限制为特定的类。

这样,Scanner 可以处理更多的类型。

如果创建了一个新类并希望它可以和 Scanner 类一起使用,那么让它实现 Readable 接口就可以了,如下所示:

java 复制代码
package interfaces;
// interfaces/RandomStrings.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Implementing an interface to conform to a method
import java.nio.*;
import java.util.*;

public class RandomStrings implements Readable {
  private static Random rand = new Random(47);
  private static final char[] CAPITALS =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
  private static final char[] LOWERS =
    "abcdefghijklmnopqrstuvwxyz".toCharArray();
  private static final char[] VOWELS =
    "aeiou".toCharArray();
  private int count;
  public RandomStrings(int count) {
    this.count = count;
  }
  @Override public int read(CharBuffer cb) {
    if(count-- == 0)
      return -1; // Indicates end of input
    cb.append(CAPITALS[rand.nextInt(CAPITALS.length)]);
    for(int i = 0; i < 4; i++) {
      cb.append(VOWELS[rand.nextInt(VOWELS.length)]);
      cb.append(LOWERS[rand.nextInt(LOWERS.length)]);
    }
    cb.append(" ");
    return 10; // Number of characters appended
  }
  public static void main(String[] args) {
    Scanner s = new Scanner(new RandomStrings(10));
    while(s.hasNext())
      System.out.println(s.next());
  }
}
/* Output:
Yazeruyac
Fowenucor
Goeazimom
Raeuuacio
Nuoadesiw
Hageaikux
Ruqicibui
Numasetih
Kuuuuozog
Waqizeyoy
*/

Readable 接口只需要实现 read() 方法(注意 @Override 是如何突出这个方法的)​。

在 read() 中,可以向参数 CharBuffer 中添加数据(有多种实现方法,请参阅 CharBuffer 文档)​,或者当没有更多输入时返回 -1。

假设有一个类型还没有实现 Readable,如何能使它与 Scanner 一起工作?下面是一个生成随机浮点数的示例:

java 复制代码
package interfaces;
// interfaces/RandomDoubles.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;

public interface RandomDoubles {
  Random RAND = new Random(47);
  default double next() { return RAND.nextDouble(); }
  static void main(String[] args) {
    RandomDoubles rd = new RandomDoubles() {};
    for(int i = 0; i < 7; i ++)
      System.out.print(rd.next() + " ");
  }
}
/* Output:
0.7271157860730044 0.5309454508634242
0.16020656493302599 0.18847866977771732
0.5166020801268457 0.2678662084200585
0.2613610344283964
*/

同样,我们可以使用适配器模式,但在这里我们通过实现两个接口来创建适配的类。

因此,使用 interface 关键字提供的多重继承,我们生成了一个新的类,它同时实现了 RandomDoubles 和 Readable:

java 复制代码
package interfaces;
// interfaces/AdaptedRandomDoubles.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Creating an adapter with inheritance
import java.nio.*;
import java.util.*;

public class AdaptedRandomDoubles
implements RandomDoubles, Readable {
  private int count;
  public AdaptedRandomDoubles(int count) {
    this.count = count;
  }
  @Override public int read(CharBuffer cb) {
    if(count-- == 0)
      return -1;
    String result = Double.toString(next()) + " ";
    cb.append(result);
    return result.length();
  }
  public static void main(String[] args) {
    Scanner s =
      new Scanner(new AdaptedRandomDoubles(7));
    while(s.hasNextDouble())
      System.out.print(s.nextDouble() + " ");
  }
}
/* Output:
0.7271157860730044 0.5309454508634242
0.16020656493302599 0.18847866977771732
0.5166020801268457 0.2678662084200585
0.2613610344283964
*/

因为任何现有类都可以通过这种方式添加接口,所以这意味着把接口作为参数的方法可以让任何类都适应它。

这就是不使用类而使用接口的威力。

10.8 接口中的字段

接口中的任何字段都自动是 static 和 final 的,因此接口是创建一组常量值的便捷工具。

在 Java 5 之前,如果想产生与 C 或 C++ 里枚举相同的效果,这是唯一的方法。

所以在 Java 5 之前你会看到像这样的代码:

java 复制代码
package interfaces;
// interfaces/Months.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using interfaces to create groups of constants

public interface Months {
  int
    JANUARY = 1, FEBRUARY = 2, MARCH = 3,
    APRIL = 4, MAY = 5, JUNE = 6, JULY = 7,
    AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10,
    NOVEMBER = 11, DECEMBER = 12;
}

请注意,Java 里具有常量初始值的 static final 字段的命名全部使用大写字母(用下划线分隔单个标识符中的多个单词)​。

接口中的字段自动为 public,因此不需要显式指定。

从 Java 5 开始,我们有了更强大、更灵活的 enum 关键字,因此有时你会希望使用它而不是接口来保存一组常量。

可以在进阶卷第 1 章找到有关 enum 的更多信息。

使用枚举来保存一组常量。

java 复制代码
public enum Months {
    JANUARY(1), 
    FEBRUARY(2), 
    MARCH(3),
    APRIL(4), 
    MAY(5), 
    JUNE(6), 
    JULY(7),
    AUGUST(8), 
    SEPTEMBER(9), 
    OCTOBER(10),
    NOVEMBER(11), 
    DECEMBER(12);

    // 定义一个私有字段来保存月份对应的数字
    private final int value;

    // 枚举的构造方法(默认是 private 的,不能写成 public)
    Months(int value) {
        this.value = value;
    }

    // 提供 getter 方法获取对应的数字
    public int getValue() {
        return value;
    }
}

初始化接口中的字段

接口中定义的字段不能是 "空白的 final"​,但它们可以用非常量表达式初始化。例如:

java 复制代码
package interfaces;
// interfaces/RandVals.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Initializing interface fields with
// non-constant initializers
import java.util.*;

public interface RandVals {
  Random RAND = new Random(47);
  int RANDOM_INT = RAND.nextInt(10);
  long RANDOM_LONG = RAND.nextLong() * 10;
  float RANDOM_FLOAT = RAND.nextLong() * 10;
  double RANDOM_DOUBLE = RAND.nextDouble() * 10;
}

这些字段都是静态的,所以它们会在类第一次加载时被初始化,首次访问该接口的任何字段都会触发这个加载。

下面是一个简单的测试:

java 复制代码
package interfaces;
// interfaces/TestRandVals.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class TestRandVals {
  public static void main(String[] args) {
    System.out.println(RandVals.RANDOM_INT);
    System.out.println(RandVals.RANDOM_LONG);
    System.out.println(RandVals.RANDOM_FLOAT);
    System.out.println(RandVals.RANDOM_DOUBLE);
  }
}
/* Output:
8
-32032247016559954
-8.5939291E18
5.779976127815049
*/

这些字段不是接口的一部分。这些值存储在该接口的静态存储区中。

10.9 嵌套接口

接口可以嵌套在类和其他接口中。这呈现了几个有趣的特性:

java 复制代码
// interfaces/nesting/NestingInterfaces.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java interfaces.nesting.NestingInterfaces}
package interfaces.nesting;

class A {
  interface B {
    void f();
  }

  public class BImp implements B {
    @Override
    public void f() {
    }
  }

  private class BImp2 implements B {
    @Override
    public void f() {
    }
  }

  public interface C {
    void f();
  }

  class CImp implements C {
    @Override
    public void f() {
    }
  }

  private class CImp2 implements C {
    @Override
    public void f() {
    }
  }

  private interface D {
    void f();
  }

  private class DImp implements D {
    @Override
    public void f() {
    }
  }

  public class DImp2 implements D {
    @Override
    public void f() {
    }
  }

  public D getD() {
    return new DImp2();
  }

  private D dRef;

  public void receiveD(D d) {
    dRef = d;
    dRef.f();
  }
}

interface E {
  interface G {
    void f();
  }

  // Redundant "public":
  public interface H {
    void f();
  }

  void g();
  // Cannot be private within an interface:
  // - private interface I {}
}

public class NestingInterfaces {
  public class BImp implements A.B {
    @Override
    public void f() {
    }
  }

  class CImp implements A.C {
    @Override
    public void f() {
    }
  }

  // Cannot implement a private interface except
  // within that interface's defining class:
  // - class DImp implements A.D {
  // - public void f() {}
  // - }
  class EImp implements E {
    @Override
    public void g() {
    }
  }

  class EGImp implements E.G {
    @Override
    public void f() {
    }
  }

  class EImp2 implements E {
    @Override
    public void g() {
    }

    class EG implements E.G {
      @Override
      public void f() {
      }
    }
  }

  public static void main(String[] args) {
    A a = new A();
    // Can't access A.D:
    // - A.D ad = a.getD();
    // Doesn't return anything but A.D:
    // - A.DImp2 di2 = a.getD();
    // Cannot access a member of the interface:
    // - a.getD().f();
    // Only another A can do anything with getD():
    A a2 = new A();
    a2.receiveD(a.getD());
  }
}

在类中嵌套接口的语法相当明显。就像非嵌套接口一样,它们可以具有 public 或包访问权限的可见性。

另外这里有个不易理解之处:接口也可以是 private 的,如 A.D 中所示(嵌套接口和嵌套类使用相同的限定语法)​。

private 的嵌套接口有什么好处?你可能会猜测,它只能作为 DImp 中的私有内部类来实现,但是 A.DImp2 表明它也可以作为 public 类来实现。

不过 A.DImp2 在使用时只能被视为自身的类型,你不能提及它实现了 private 的接口 D。

所以实现了 private 接口的话,可以在不添加任何类型信息的情况下,限定该接口中的方法定义(也就是说,不允许任何向上转型)​。

方法 getD() 让我们进一步陷入困境,这与 private 接口有关:它是一个 public 方法,但返回了一个 private 接口的引用。

可以对这个方法的返回值做些什么?在 main() 里我们多次尝试使用该返回值,但都失败了。

该返回值必须传递给一个有权使用它的对象------这里是另一个 A,它可以通过 receiveD() 方法使用这个返回值。

接口 E 表明,接口之间也可以嵌套。

然而,关于接口的规则------特别是所有接口元素必须是 public 的------在这里是严格执行的,

所以嵌套在另一个接口中的接口自动为 public 的,不能设为 private。

NestingInterfaces 展示了实现嵌套接口的各种方式。

特别要注意的是,当实现一个接口时,并不需要实现嵌套在其中的接口。

此外,private 接口不能在它们的定义类之外实现。

初看起来,这些特性好像仅仅是为了语法一致性而添加的,但我通常发现,一旦了解了一个特性,你就会经常发现它的有用之处。

10.10 接口和工厂

接口是通向多个实现的网关,如果想生成适合某个接口的对象,一种典型的方式是工厂方法 (Factory Method) 设计模式。

你不是直接调用构造器,而是在工厂对象上调用创建方法,它可以产生接口实现。

这样,理论上,你的代码与接口实现完全隔离,从而可以透明地将一种实现替换为另一种实现。

下面是一个示例,展示了工厂方法的结构:

java 复制代码
package interfaces;
// interfaces/Factories.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

interface Service {
  void method1();

  void method2();
}

interface ServiceFactory {
  Service getService();
}

class Service1 implements Service {
  Service1() {
  } // Package access

  @Override
  public void method1() {
    System.out.println("Service1 method1");
  }

  @Override
  public void method2() {
    System.out.println("Service1 method2");
  }
}

class Service1Factory implements ServiceFactory {
  @Override
  public Service getService() {
    return new Service1();
  }
}

class Service2 implements Service {
  Service2() {
  } // Package access

  @Override
  public void method1() {
    System.out.println("Service2 method1");
  }

  @Override
  public void method2() {
    System.out.println("Service2 method2");
  }
}

class Service2Factory implements ServiceFactory {
  @Override
  public Service getService() {
    return new Service2();
  }
}

public class Factories {
  public static void serviceConsumer(ServiceFactory fact) {
    Service s = fact.getService();
    s.method1();
    s.method2();
  }

  public static void main(String[] args) {
    serviceConsumer(new Service1Factory());
    // Services are completely interchangeable:
    serviceConsumer(new Service2Factory());
  }
}
/*
 * Output:
 * Service1 method1
 * Service1 method2
 * Service2 method1
 * Service2 method2
 */

如果没有工厂方法,你的代码必须在某处指定创建 Service 的确切类型,以调用相应的构造器。

为什么要添加这种额外的间接层?一个常见的原因是创建框架。

假设你正在创建一个系统来玩游戏,例如想要在同一个棋盘上玩国际象棋和跳棋:

java 复制代码
package interfaces;
// interfaces/Games.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// A Game framework using Factory Methods

interface Game {
  boolean move();
}

interface GameFactory {
  Game getGame();
}

class Checkers implements Game {
  private int moves = 0;
  private static final int MOVES = 3;

  @Override
  public boolean move() {
    System.out.println("Checkers move " + moves);
    return ++moves != MOVES;
  }
}

class CheckersFactory implements GameFactory {
  @Override
  public Game getGame() {
    return new Checkers();
  }
}

class Chess implements Game {
  private int moves = 0;
  private static final int MOVES = 4;

  @Override
  public boolean move() {
    System.out.println("Chess move " + moves);
    return ++moves != MOVES;
  }
}

class ChessFactory implements GameFactory {
  @Override
  public Game getGame() {
    return new Chess();
  }
}

public class Games {
  public static void playGame(GameFactory factory) {
    Game s = factory.getGame();
    while (s.move())
      ;
  }

  public static void main(String[] args) {
    playGame(new CheckersFactory());
    playGame(new ChessFactory());
  }
}
/*
 * Output:
 * Checkers move 0
 * Checkers move 1
 * Checkers move 2
 * Chess move 0
 * Chess move 1
 * Chess move 2
 * Chess move 3
 */

如果 Games 类代表了一段复杂的代码,这种方式意味着你可以在不同类型的游戏中复用该代码。

可以想象,更加复杂的游戏可以从这种模式中受益。

10.11 新特性:接口的 private 方法

随着 default 和 static 方法引入接口,我们可以在接口中编写方法的代码了,但同时可能不想让这些方法成为 public 的。

在 Old 类中,fd() 和 fs() 分别是 default 和 static 方法。

这些方法只被 f() 和 g() 调用,所以我们希望它们是 private 的:

java 复制代码
package interfaces;
// interfaces/PrivateInterfaceMethods.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 9

interface Old {
  default void fd() {
    System.out.println("Old::fd()");
  }

  static void fs() {
    System.out.println("Old::fs()");
  }

  default void f() {
    fd();
  }

  static void g() {
    fs();
  }
}

class ImplOld implements Old {
}

interface JDK9 {
  private void fd() { // Automatically default
    System.out.println("JDK9::fd()");
  }

  private static void fs() {
    System.out.println("JDK9::fs()");
  }

  default void f() {
    fd();
  }

  static void g() {
    fs();
  }
}

class ImplJDK9 implements JDK9 {
}

public class PrivateInterfaceMethods {
  public static void main(String[] args) {
    new ImplOld().f();
    Old.g();
    new ImplJDK9().f();
    JDK9.g();
  }
}
/*
 * Output:
 * Old::fd()
 * Old::fs()
 * JDK9::fd()
 * JDK9::fs()
 */

接口 JDK9 使用了 JDK 9 里的新特性,将 fd() 和 fs() 转换为private方法。

注意,fd() 不再需要 default 关键字,因为变成 private 后自动就是 default 的了。

10.12 新特性:密封类和密封接口

枚举创建了一个只有固定数量实例的类。

JDK 17 最终确定引入了密封 (sealed) 类和密封接口,因此基类或接口可以限制自己能派生出哪些类。

这让我们可以对一组固定种类的值进行建模:

java 复制代码
package interfaces;
// interfaces/Sealed.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed class Base permits D1, D2 {}

final class D1 extends Base {}
final class D2 extends Base {}
// Illegal:
final class D3 extends Base {}

如果尝试继承未在 permits 子句中列出的子类,比如 D3,则编译器会产生错误。

在这里,除了 D1 和 D2 之外,不能有任何其他子类。

因此,我们可以确保自己编写的任何代码都只需要考虑 D1 和 D2。

还可以密封接口和抽象类:

java 复制代码
package interfaces;
// interfaces/SealedInterface.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed interface Ifc permits Imp1, Imp2 {}
final class Imp1 implements Ifc {}
final class Imp2 implements Ifc {}

sealed abstract class AC permits X {}
final class X extends AC {}

如果所有的子类都定义在同一个文件中,则不需要 permits 子句:

java 复制代码
package interfaces;
// interfaces/SameFile.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed class Shape {}
final class Circle extends Shape {}
final class Triangle extends Shape {}

permits 子句允许我们在单独的文件中定义子类:

java 复制代码
package interfaces;
// interfaces/SealedPets.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17
sealed class Pet permits Dog, Cat {}
java 复制代码
package interfaces;
// interfaces/SealedDog.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17
final class Dog extends Pet {}
java 复制代码
package interfaces;
// interfaces/SealedCat.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17
final class Cat extends Pet {}

sealed 类的子类只能通过下面的某个修饰符来定义。

  • final:不允许有进一步的子类。
  • sealed:允许有一组密封子类。
  • non-sealed:一个新关键字,允许未知的子类来继承它。

sealed 的子类保持了对层次结构的严格控制:

java 复制代码
package interfaces;
// interfaces/SealedSubclasses.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed class Bottom permits Level1 {}
sealed class Level1 extends Bottom permits Level2 {}
sealed class Level2 extends Level1 permits Level3 {}
final class Level3 extends Level2 {}

注意,一个 sealed 类必须至少有一个子类。

一个 sealed 的基类无法阻止 non-sealed 的子类的使用,因此可以随时放开限制:

java 复制代码
package interfaces;
// interfaces/NonSealed.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed class Super permits Sub1, Sub2 {}
final class Sub1 extends Super {}
non-sealed class Sub2 extends Super {}
class Any1 extends Sub2 {}
class Any2 extends Sub2 {}

Sub2 允许任意数量的子类,因此它似乎放开了对可以创建的类型的控制。

但是,我们还是严格限制了 sealed 类 Super 的直接子类。也就是说,Super 仍然只能有直接子类 Sub1 和 Sub2。

JDK 16 的 record 也可以用作接口的密封实现。因为 record 是隐式的 final,所以它们不需要在前面加 final 关键字:

java 复制代码
package interfaces;
// interfaces/SealedRecords.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed interface Employee
    permits CLevel, Programmer {
}

record CLevel(String type)
    implements Employee {
}

record Programmer(String experience)
    implements Employee {
}

编译器会阻止我们从密封层次结构中向下转型为非法类型:

java 复制代码
package interfaces;
// interfaces/CheckedDowncast.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed interface II permits JJ {}
final class JJ implements II {}
class Something {}

public class CheckedDowncast {
  public void f() {
    II i = new JJ();
    JJ j = (JJ)i;
    // Something s = (Something)i;
    // error: incompatible types: II cannot
    // be converted to Something
  }
}

可以在运行时使用 getPermittedSubclasses() 方法来发现允许的子类:

java 复制代码
package interfaces;
// interfaces/PermittedSubclasses.java

// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {NewFeature} Since JDK 17

sealed class Color permits Red, Green, Blue {
}

final class Red extends Color {
}

final class Green extends Color {
}

final class Blue extends Color {
}

public class PermittedSubclasses {
  public static void main(String[] args) {
    for (var p : Color.class.getPermittedSubclasses())
      System.out.println(p.getSimpleName());
  }
}
/*
 * Output:
 * Red
 * Green
 * Blue
 */

sealed 类和接口最引人注目的用法将在进阶卷第 1 章的末尾介绍,其中包括新引入的模式匹配特性。

10.13 总结

我们可能很容易就会觉得接口是好的,因此总是选择接口而不是具体的类。几乎任何要创建一个类的场景,都可以创建一个接口和一个工厂来代替。

许多人受到了这种诱惑,只要有可能就创建接口和工厂。这里的逻辑似乎是,你可能会用到不同的实现,因此应该始终添加这层抽象。这是一种过早的设计优化。

任何抽象都应该由真正的需求来驱动。接口应该是在必要时用来重构的东西,而不是在任何地方都多加一个间接层级,进而带来额外的复杂性。这种额外的复杂性影响很大,如果你让某人在克服这种复杂性上花费时间,而他最终却发现你添加接口只不过是为了 "以防万一"​,而非出于什么令人信服的其他理由------那好吧,如果我看到这样的设计,就会开始质疑这个人做过的其他所有设计。

一个比较恰当的指导方针是 "优先使用类而不是接口"​。从类开始设计,如果很明显接口是必要的,那么就重构。接口是一个很好的工具,但它很容易被滥用。

相关推荐
虎符饼干1 小时前
用WebHook把AI文章推送到自建官网,接收端需要具备哪些处理与发布能力?
笔记
吃我一窝jio1 小时前
Java多线程核心知识点梳理
java·开发语言·笔记
星恒随风2 小时前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
geovindu2 小时前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
geovindu3 小时前
python:Lasso
开发语言·后端·python·算法
aaaameliaaa3 小时前
VSCode的安装与配置
ide·笔记·vscode·编辑器
这个昵称不容易3 小时前
在线考试系统设计与实现:14 张表 158 个接口,组卷、答题、判分一条线走通
java·springboot·毕设
多加点辣也没关系3 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
码云社区3 小时前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序