开发者

Class method behavior during inheritence

开发者 https://www.devze.com 2022-12-12 06:27 出处:网络
class A #define class level attribute called key class 开发者_高级运维<< self attr_accessor :key
class A
  #define class level attribute called key
  class 开发者_高级运维<< self
    attr_accessor :key
  end
end

class B < A
end

B.key = "foo"
B.key # returns "foo"
A.key # returns nil

.

What is the approach if I want A.key to return "foo" in the above scenario?


The only way I know is to manually declare the class functions. Subclasses will return the parent's value, but you cannot have them return a different value.

class A
  def self.key
    @@key
  end

  def self.key=(new_val)
    @@key = new_val
  end
end


Class methods can't be virtual. C'est la vie. When you have a class, you have no virtual table.

0

精彩评论

暂无评论...
验证码 换一张
取 消