1

I'm calling a method from the Superclass called getStringRepresentation which currently returns " ". Which is fine. My problem is I want to change the return statement in my Subclass to another symbol such as S or O for example.

Currently my code looks like this:

public EmptySpace(Position position) {
    super(position);
    super.getStringRepresentation()
        return "ES"; //this obviously doesn't work.
}

I understand with a string you can just override it with system.out, but the java tutorials don't explain or have an example for return statements. but the java tutorials don't explain or have an example for return statements.

Main class

    public class Sector
    {
    private Position            position;

 /**
 * Returns a String containing " " (Whitespace).
 * 
 * @Return returns a String containg " "
 */
 public String getStringRepresentation() {

    return " ";

 }
2
  • It's not clear whether your code is part of the superclass or subclass. Please post the relevant portions of both so that we can see how they fit together. Commented Mar 23, 2014 at 10:29
  • You cannot return anything from constructor. Commented Mar 23, 2014 at 10:30

2 Answers 2

1

Don't call the getStringRepresentation() method from the constructor of subclass.

Instead override the getStringRepresentation() method in your subclass.

public EmptySpace(Position position) {
   super(position);
}

@Override
public String getStringRepresentation() {
  return "ES";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Override the method in your EmptySpace class:

public EmptySpace(Position position) {

    super(position);

}

@Override
public String getStringRepresentation() {
    return "ES";
}

2 Comments

Hey Roberto I had that later in the method, but isn't the purpose of inheritance that you don't need to create new methods that exist in the superclass?
That is the way to go if you want to modify the behaviour of the existing method. That is, due to inheritance you don't need to do it if the parent method implementation returns what you need, otherwise you have to implement your modified version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.