Instance Variables Inheritance

前端 未结 4 730
孤城傲影
孤城傲影 2021-02-12 17:08

Can someone explain how a class can access the instance variables of its superclass and how that is not inheritance? I\'m talking about \'The Ruby Programming Language\' and the

4条回答
  •  忘了有多久
    2021-02-12 17:36

    You are right, the book is wrong, or at least poorly worded


    I would argue that the book is simply wrong, or at best, it's making a quite muddy explanation.

    In all OO languages, the superclass and derived class don't have separate objects. When you create an instance of the derived class, it is also an instance of the superclass. There is one object and it is both classes at once.

    Since there is only one object, there is only one set of instance variables.

    This is the same as all other OO systems. The weird argument that book makes about how it just matters which method is run and how the methods themselves are what are really inherited does not add much in the way of clarity.

    The problem with the terminology is that, sure, in a dynamically typed system there is no declaration in the first place, and so certainly the definition of the subclass doesn't inherit any field declarations ... because of course there aren't any. But just because there are no types to inherit doesn't make the opposite statement ("instance variables are not inherited") any more true, and it adds quite a bit of confusion because it implies that somehow the parent would have different instance variables, which is the nonsensical result of trying to talk about the objects the way they do.

提交回复
热议问题