Why is System.out.println(super) not permitted?
System.out.println(this);
This is OK and this.toString() is called and printed automatically.
Of course, instance variable is OK instead of this.
However, this and super can be used in same way as I know.
System.out.println(super);
So why does this fail? I think it's supposed to call super.toString() implicitly.
I have read Java specification document, but I haven't found the reason.
Check the grammar at http://java.sun.com/docs/books/jls/second_edition/html/syntax.doc.html
The super keywords must always be followed by SuperSuffix, which cannot be empty.
So super can never stand alone as an expression.
Implementing a standalone variant of super that breaks virtual method dispatch would be an extremely bad idea.
Let's think about it for a while.
abstract class Base {
abstract String Description();
String toString() { return "Base"; }
}
class Derived extends Base {
String Description() { return "Derived description"; }
String toString() { return "Derived"; }
static void use(Base instance) {
System.out.println(instance.toString());
System.out.println(instance.Description());
}
}
Now, let us take your suggestion and suppose that super is valid and does what you suggest; then we may write in Derived:
class Derived extends Base {
// Previous declarations omitted.
void useSuper() { Derived.use(super); }
void useThis() { Derived.use(this); }
static void main() {
Derived instance = new Derived();
instance.useThis();
instance.useSuper();
}
}
Now, if I understood you, you suggest that the main function should print in order:
toString() from Derived: "Derived".Description() from Derived: "Derived description"toString() from Base: "Base".Description() from Base: It does not exist. And the two solutions I can think of leads to bigger problems:
Derived: breaks consistency.In short, such a use of the word super conceptually breaks object-oriented programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With