Why can I not use “super” variable from a static context, even though “super” refers to the parent class and NOT a class instance, unlike “this”?

前端 未结 4 653
一向
一向 2020-12-28 21:09

I\'m talking java language.

Variable \"this\", when used inside a class, refers to the current instance of that class, which means you cannot use \"this\" inside a s

相关标签:
4条回答
  • 2020-12-28 21:35

    Here is the section in the JLS about the super keyword:

    http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.11.2

    The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

    The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.

    In both cases, it is clear that an instance object is needed.


    Also, a static context is somewhat different from an instance context, as a class can't override static methods, only hide them.

    0 讨论(0)
  • 2020-12-28 21:45

    Super is a non static variable and non static entity cannot be accessed from static context.

    0 讨论(0)
  • 2020-12-28 21:49

    No, super does refer to an instance -- the same instance that this refers to -- the current object. It's just a way to reference methods and fields in defined in the superclass that are overridden or hidden in the current class.

    0 讨论(0)
  • 2020-12-28 21:56

    You can't use super from a static context for the same reason you can't use this in a static context. In both cases, the word refers to an instance.

    In a static context, you can always use the name of the superclass explicitly:

    class Sub extends Base {
        static void func() {
            Base.func();
            . . .
        }
    }
    
    0 讨论(0)
提交回复
热议问题