How does the “this” keyword in Java inheritance work?

后端 未结 7 791
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 09:23

In the below code snippet, the result is really confusing.

public class TestInheritance {
    public static void main(String[] args) {
        new Son();
                


        
7条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 10:06

    As other stated, you cannot override fields, you can only hide them. See JLS 8.3. Field Declarations

    If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.

    In this respect, hiding of fields differs from hiding of methods (§8.4.8.3), for there is no distinction drawn between static and non-static fields in field hiding whereas a distinction is drawn between static and non-static methods in method hiding.

    A hidden field can be accessed by using a qualified name (§6.5.6.2) if it is static, or by using a field access expression that contains the keyword super (§15.11.2) or a cast to a superclass type.

    In this respect, hiding of fields is similar to hiding of methods.

    A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

    You can access Father's hidden fields from Son's scope using super keyword, but the opposite is impossible since Father class is not aware of its subclasses.

提交回复
热议问题