1

BaseExample 类(我不允许在此示例中使变量受保护):

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);
    }


}

派生示例类:

public class DerivedExample extends BaseExample {
    private int b;



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

    }
}

超级方法奏效了。现在,如果我被问到这个,我该怎么称呼它:

**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()**

我试过这个:

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

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

        }

如果我放了两个返回,它会给我一个无法访问代码的错误。如果我在 valueOf 里面放了一个 super ,它就不起作用了。这也行不通。这是如何执行的?

4

1 回答 1

1

我认为您误解了要求,您需要打印a位于父类中的内容,由与当前类中的 b 连接的冒号分隔。

String.valueOf(base:this.b)

这是不正确的语法,你想要的是

super.toString() + ":" + this.b;
于 2015-05-26T19:32:05.473 回答