Search code examples
javaclassprivatetostringvalue-of

.valueOf using another class's private variable


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?


Solution

  • 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;