1

BaseExample Class (I am not allowed to make the variable protected on this example):

public class BaseExample {
    private int a;

    public BaseExample(int inVal) {
        a = inVal;
    }

    public BaseExample(BaseExample other){
        a = other.a;
    }

    public String toString(){
        return String.valueOf(a);
    }


}

DerivedExample Class:

public class DerivedExample extends BaseExample {
    private int b;



public DerivedExample(int inVal1, int inVal2){
        super(inVal2);
        a = inVal2;

    }
}

The super method worked. Now how would I call it if I am asked this:

**Returns a reference to a string containing the value stored in the inherited varible a followed by a colon followed by the value stored in b public String toString()**

I have tried this:

public String toString(){
            int base = new BaseExample(b);

            return String.valueOf(base:this.b);

        }

If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?

userb
  • 173
  • 2
  • 15

1 Answers1

1

I think you misunderstood the requirement, you need to print a which is located in the parent class separated by a colon concatenated with b which is in the current class.

String.valueOf(base:this.b)

This is incorrect syntax, what you want is

super.toString() + ":" + this.b;
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • and of course to be clear he should put `return` in front of that – D. Ben Knoble May 26 '15 at 19:32
  • @BenKnoble And the return statement should be in a method, and the method in a class declaration, and the class declaration in a .java class... He already use `return`. – Jean-François Savard May 26 '15 at 19:40
  • Ah. It makes total sense now. I definitely interpreted that colon to be inside the valueOf(). Thank you. – userb May 26 '15 at 19:42
  • Why are you using `.concat()`? Why not just `super.toString() + ":" + this.b`? Sure, the same things are happening on the back end, but this way is more readable and simpler. – Mar May 26 '15 at 20:45
  • @MartinCarney I was drunk. Note that not exactly *"the same things are happening on the back end"*, but I would still not use it in this case. http://stackoverflow.com/questions/47605/string-concatenation-concat-vs-operator – Jean-François Savard May 26 '15 at 22:13
  • @Jean-FrançoisSavard I'm guessing you missed to Ballmer Peak? https://xkcd.com/323/ (I know it's not *exactly* the same stuff happening on the back end, but close enough for government work.) – Mar May 26 '15 at 22:17
  • @MartinCarney Rofl you made my day with that link. – Jean-François Savard May 26 '15 at 22:18