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

旧巷老猫 提交于 2019-12-05 07:46:10

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.

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.

this refers to your current object. super refers to the super class, the class your current object directly inherits from (or it can be the super's constructor). So

System.out.println(this)

prints your object's toString() method, but

System.out.println(super)

fails because super is NOT an object (and thus has no toString() method).

Super is relevant for calling of static methods only. If you call non-static method using super that is actually reference to your object itself, i.e. to this. For example you can say System.out.println(super.toString()). This will work and will run the toString() of actual class.

I think this is the reason that passing super as argument to other method is forbidden.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!