0

Answer という抽象クラスがあります。仮説的には、文字列の回答、ビデオの回答、音声の回答など、さまざまな種類の回答が存在する可能性があるため、抽象化する必要があります。

public abstract class Answer {

abstract public void display();

abstract public Answer getAnswer();

abstract public boolean isEqual();

}

StringAnswer では、これらのメソッドをオーバーライドしたいと考えています。

public class StringAnswer extends Answer
{
String text;

public StringAnswer(String text)
{
    this.text = text;
}

@Override
public void display()
{
    System.out.println(text);
}

@Override
**public String getAnswer()
{
    return text;
}**

@Override
public boolean isEqual()
{
    // TODO Auto-generated method stub
    return false;
}
}

getAnswer は、文字列を返そうとしているため問題を引き起こしていますが、回答が返されることを期待しています。抽象的な意味で、私は Answer を返したいです。ただし、StringAnswer の内容は明らかに String になります。

では、回答を期待しているときに文字列として返すにはどうすればよいですか?

4

4 に答える 4

7

あなたはそうしない。デザインを修正します。

あなたが望むかもしれないのは次のようなものだと思います

abstract class Answer<T> {
  public abstract T getAnswer();
}

public class StringAnswer extends Answer<String> {
  public String getAnswer() { ... }
}
于 2012-10-19T03:22:55.297 に答える
1

When you override a method, you have this rules (from other rules):

The return type must be the same or a child of the return type in the overridden method.

Given this, String doesn't extends Answer, so your getAnswer override would be wrong.

You have two ways to fix the method:

//1st way
@Override
public Answer getAnswer() {
    return this;
}

//2nd way
@Override
public StringAnswer getAnswer() {
    return this;
}

You should choose your way (hint: change my implementation of the override method!).

于 2012-10-19T03:23:03.510 に答える
1

This is what generic is for. You can view the manual here:

http://docs.oracle.com/javase/tutorial/java/generics/

于 2012-10-19T03:23:37.067 に答える
1

First you need to understand the difference between an abstract class and an interface. An interface specifies a list of properties or methods that a class must implement. This would probably be more appropriate for your example. An abstract class specifies some functionality, usually with a few concrete implementations, and then some abstract methods which are sort of similar to an interface, that must be implemented.

Since you are not adding any functionality in your base class, I suggest an interface

于 2012-10-19T03:23:41.667 に答える