Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.out.println(super) not permitted?

Tags:

java

oop

tostring

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.

like image 537
JaycePark Avatar asked Jul 22 '11 05:07

JaycePark


2 Answers

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.

like image 195
Ray Toal Avatar answered Oct 24 '22 15:10

Ray Toal


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:

  • the implementation of toString() from Derived: "Derived".
  • the implementation of Description() from Derived: "Derived description"
  • the implementation of toString() from Base: "Base".
  • the implementation of Description() from Base: It does not exist. And the two solutions I can think of leads to bigger problems:
    • Raise an exception: congratulations, you can now break any program which relies on abstract methods actually being implemented without even thinking about it. (How would you know that a function will call the abstract method?)
    • Return the implementation from Derived: breaks consistency.

In short, such a use of the word super conceptually breaks object-oriented programming.

like image 42
Jean Hominal Avatar answered Oct 24 '22 17:10

Jean Hominal