开发者

super-keyword in Java giving compile-error

class That {
    protected String nm() {
        return "That";
    }
}

class More extends That {
    protected String nm() {
        return "More";
    }

    protected void printNM() {
        That sref = super;

        System.out.println("this.nm() = " + this.nm());
        System.out.println("sref.nm() = " + sref.nm());
        System.out.println("super.nm() = " + super.nm());
    }

    public static void main(String[] args) {
        new More().printNM();
    }
}

When trying to compile More.java I'm getting 4 errors:

More.java:7: error: '.' expected
                That sref = super;
                                 ^
More.java:7: error: ';' expected
                That sref = super;
            开发者_如何学Go                      ^
More.java:9: error: illegal start of expression
                System.out.println("this.nm() = " + this.nm());
                      ^
More.java:9: error: ';' expected
                System.out.println("this.nm() = " + this.nm());
                          ^
4 errors

Is something wrong with the code? (It's from the book "The Java Programming Language" p.62)

EDIT: From the book: "And here is the output of printNM:

this.nm() = More
sref.nm() = More
super.nm() = That

So either they're using some deprecated super-feature(I think this is the first edition of the book) or it is a typo and maybe they meant: "That sref = new More()"


You can't use super that way. Either use it in a constructor, with brackets - super() or super.method() (or in generics)

In your case this keyword shouldn't be there. If you want an instance of the super class, just have

That sref = new That();


Change : That sref = super; to That sref = super();

This statement is basically trying to get hold of the object reference of the super class type, so you need to call the constructor for it - which is done using super().


Simply stated, you can't. You probably could do some hacks through reflection, but side from that you can't do it. You need to know what class you're making your new Object. In this case, you have to make it new That().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜