java - 接口(interface)中没有设置方法

标签 java inheritance interface

我有一个实现接口(interface) B 的具体类 A。

B ref = new A();

代码:

public interface B{
  public abstract String[] getWords();
}

public class A implements B {
  private String[] words = new String[] {};
  public void setWords(String[] words){
    this.words = words;
  }
  public String[] getWords(){
    return this.words;
  }
 }

在接口(interface) B 中,我只有 getter 方法而没有 setter 方法,尽管类 A 有它。

所以当我这样做时:B ref = new A();,这段代码会起作用吗?我将如何设置单词?

最佳答案

如果 ref 被定义为 B ref = ...,您将无法调用 setWords

这是在声明变量(或使用强制转换)时需要使用确切类型的情况之一:

A ref = new A();

或者:

  • 您可以创建一个扩展 B 并包含两种方法的接口(interface) C,并让 A 实现 C。
  • 您可以在 A 中提供一个构造函数,它采用 String[] words 参数来初始化您的 words 字段,并且根本不提供 setter。

我个人倾向于后一种选择:

public class A implements B {

    private final String[] words;

    public A(String[] words) {
        this.words = words;
    }

    public String[] getWords() {
        return this.words;
    }
}

关于java - 接口(interface)中没有设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950648/

相关文章:

java - 从具有具体子类的抽象类实现 Comparable 接口(interface)

c# - 为什么接口(interface)变量实例化是可能的?

C# 泛型方法类型参数不是从用法中推断出来的

java - 我们有什么工具可以将 Android xml 布局转换为 .java 文件吗?

java - 在接缝中自定义#{currentDate} 的格式?

java - 使用 Java 将 xml 字符串 POST 到 URL

c# - 基类实现抽象时在派生类中指定实现接口(interface)

c++ - 如何不使用虚拟继承?

java - Grpc 无法解析符号 GreeterGrpc

c++ - C++中基类对象和派生类对象的大小