Instance Variables Inheritance

前端 未结 4 725
孤城傲影
孤城傲影 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:16

    You can compare these two examples.

    example 1: it seems B inherit @i from A.

    class A
      def initialize()
        @i = "ok"
      end
    end
    
    class B < A
      def print_i()
        p(@i)
      end
    end
    
    B.new().print_i()   # Shows "ok"
    

    example 2: if B has its own initialize(), it cannot find @i.

    class A
      def initialize()
        @i = "ok"
      end
    end
    
    class B < A
      def initialize()
      end
    
      def print_i()
        p(@i)
      end
    end
    
    B.new().print_i()   # nil, print nothing
    

    class B's @i in example 1, is actually created implicitly by A#initialize() when you invoke B.new().

    In your case, @x and @y in Point3D is actually created by Point#initialize(), not inherited from Point

提交回复
热议问题