gpt4 book ai didi

java - 接口(interface)使用

转载 作者:行者123 更新时间:2023-11-30 06:29:14 25 4
gpt4 key购买 nike

能否有一个类实现了一个接口(interface),在这个类实例化的时候选择是否使用接口(interface)中的方法?因此有使用接口(interface)的对象 A 和不使用接口(interface)的对象 B。

谢谢

更新:

假设你有一个 Professor 类,这个类实现了一个名为 Employer 的接口(interface),它有 employ(rAssist x) 抽象方法。

现在我想实例化实现此接口(interface)的 Professor 类中的 2 个对象 Object A - Professor can employ a research assistant and Object B - Professor cannot employ research assistants。

最佳答案

Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class?

不,如果 C 类实现了该接口(interface),则 C 的所有实例都将提供接口(interface)中声明的方法。

你可以做的是类似

class MyClass implements MyInterface {

@Override
void interfaceMethod() {
System.out.println("Interface method");
}
}

然后做

MyClass x = new MyClass();

MyClass y = new MyClass() {
@Override
void interfaceMethod() {
throw new UnsupportedOperationException();
}
};

实际上,x 支持使用 interfaceMethody 不支持。但是请注意...

  • y.interfaceMethod 的使用在编译时 不会被阻止,即它不会被类型系统强制执行。

  • 使用此解决方案,您实际上是在创建 MyClass 的(匿名)子类,并将其实例分配给 y.

关于java - 接口(interface)使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11715746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com