How does instance variable invocation work when you do A thing = new B(); where B is a subclass of A?

前端 未结 6 752
予麋鹿
予麋鹿 2021-01-27 17:54

This is probably answered somewhere, but I have no idea what to search for. Imagine you have the following...

The superclass, Animal.java

public class An         


        
6条回答
  •  粉色の甜心
    2021-01-27 18:49

    Short answer:

    You can override methods, but it's not possible to override fields.

    Long answer:

    Each class sees the methods and fields of it's own and of it's parents (except for private methods). If the child delcares a method, whose name is the same, as the name of the method in his parent class, this method becomes overridden - if this method is somehow invoked on the child instance (even from the one of the parent's methods), the brand new method will be used instead of the parent's one. Child may still call the original method of his last parent via super.method(...) call.

    But the story is different when we come to the fields. If the child declares a new field, that is named exactly as the field in parent class, it will simply hide the parent's field without overriding, just like the local variable hides global one. So the child methods will simply see the child's fields, but the parent's method will continue to see parent's field, and child's field will not be visible by any means from the parent class - that's what you've got.

    Child can access the field of it's parent via ((Parent)this).field.

提交回复
热议问题