keyword super

J

josh

If I have a method in my subclass returning a String and I
make>>>>> return super
why does not the compiler call toString() method ?
is it not equal to keyword "this"?
 
T

Tymoteusz Gedliczka

josh said:
If I have a method in my subclass returning a String and I
make>>>>> return super
why does not the compiler call toString() method ?
is it not equal to keyword "this"?

Keyword super by itself doesn't reference to any object, nor call any
method, so you can't just "return super;"

You can use super in two ways:

- to call constructor of the superclass, call super(). There are,
however, limitations: you can use it only in first line of any
constructor. Definitely, it is useless for your purpose.

- to reference some method from superclass you use syntax:
super.methodFromSuperClass()

What you probably want to do is to call:
return super.toString();
 
O

Oliver Wong

josh said:
If I have a method in my subclass returning a String and I
make>>>>> return super
why does not the compiler call toString() method ?
is it not equal to keyword "this"?

Notice that the "this" keyword does not auto-invoke toString() or anything
like that. The following code will NOT compile:

public class Foo {
public String methodReturningString() {
return this;
}
}

- Oliver
 
M

Mark Rafn

josh said:
If I have a method in my subclass returning a String and I
make>>>>> return super
why does not the compiler call toString() method ?
is it not equal to keyword "this"?

This would be clearer if you included a tiny example that showed what you want
to do. But the answer is twofold:

1) super is not a reference to a type, it's a way to un-override uses of
methods and members. this.foo() and super.foo() both call foo() on the
"this" object, but super.foo() runs the code in the superclass rather than
in this class. You can't return super in the same way you can return this,
because there is no distinct super object, it's effectively just part of this.

2) You can't return an object (not even "this") from a method that returns
String anyway. You can only return a String. You can return this.toString(),
or you can return super.toString().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,197
Latest member
Sean29G025

Latest Threads

Top