Question

I have an abstract class called Answer. It needs to be abstract because hypothetically, there can be many different types of Answers such as String answers, video answers, audio answers, etc.

public abstract class Answer {

abstract public void display();

abstract public Answer getAnswer();

abstract public boolean isEqual();

}

Now in StringAnswer, I want to override these methods.

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 is giving me problems because I'm trying to return a String, but it's expecting an Answer back. In the abstract sense, I want to return an Answer. However, the content of StringAnswer is obviously going to be a String.

So, how do I return it as a String when it's expecting an Answer?

Was it helpful?

Solution

You don't. You fix your design.

I suspect what you might want is something like

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

public class StringAnswer extends Answer<String> {
  public String getAnswer() { ... }
}

OTHER TIPS

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!).

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top