6

我有一个实现接口 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;
  }
 }

在接口 B 中,虽然类 A 有它,但我只有 getter 方法但没有 setter 方法。

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

4

5 回答 5

5

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

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

A ref = new A();

或者:

  • 您可以创建一个接口 C 扩展 B 并包含这两种方法并让 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;
    }
}
于 2012-12-19T10:50:42.943 回答
5

所以当我这样做时:B ref = new A();,这段代码会起作用吗?

是的,它会的。

...我将如何设置单词?

你将无法做到,除非你:

  1. makeA的构造函数获取单词列表;或者
  2. 添加setWords()B; 或者
  3. 保留对A对象的类型引用;或者
  4. 沮丧refA

其中,我会选择选项 1-3 之一。最后一个选项仅出于完整性考虑。

于 2012-12-19T10:51:27.273 回答
4

如果接口确实公开了它,则必须转换回原始类型

if (ref instanceof A)
   ((A) ref).setWords(words);
else
   // something else.

更好的解决方案是将方法添加到接口中。

于 2012-12-19T10:51:53.717 回答
3
B ref = new A();//1
ref.setWords(whatever);//2

上面的代码不会像setWords()interface B的 .

正如其他人已经在他们的答案中表达的那样。你有 2 个选项作为解决方法

  • 创建对象为 A ref = A();
  • 将 ref 向下转换为 A 类型,例如 ((A)ref).setWords(watever);
于 2012-12-19T10:51:31.400 回答
0

所以当我这样做时:B ref = new A();,这段代码会工作吗

是的

我将如何设置单词?

你不能。你需要在你的界面中有setter方法。

在您之间不需要将方法定义为抽象的。默认情况下是抽象的。

于 2012-12-19T10:53:29.007 回答