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

后端 未结 7 659
被撕碎了的回忆
被撕碎了的回忆 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:18

    While methods can be overridden, attributes can be hidden.

    In your case, the attribute x is hidden: in your Son class, you can't access the Father's x value unless you use the super keyword. The Father class doesn't know about the Son's x attribute.

    In the opposit, the toString() method is overriden: the implementation that will always be called is the one of the instantiated class (unless it does not override it), i.e. in your case Son, whatever the variable's type (Object, Father...).

    0 讨论(0)
提交回复
热议问题