sadsadasssssa
sadsadasssssa

Reputation: 21

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;
                                  ^
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()"

Upvotes: 2

Views: 747

Answers (3)

Bozho
Bozho

Reputation: 597382

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

Upvotes: 2

corsiKa
corsiKa

Reputation: 82589

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

Upvotes: 0

Saket
Saket

Reputation: 46157

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

Upvotes: 0

Related Questions