1

How to implement inheritance in ruby for the following?

class Land
  attr_accessor :name, :area
  def initialize(name, area)
    @name = name
    @area = area
  end
end

class Forest < Land
  attr_accessor :rain_level
  attr_reader :name

  def name=(_name)
    begin
      raise "could not set name"
    rescue  Exception => e
            puts e.message  
        end
  end

  def initialize(land, rain_level)
    @name = land.name
    @rain_level = rain_level
  end
end

l = Land.new("land", 2300)
f = Forest.new(l, 400)
puts f.name # => "land"    

suppose when i change name for land l, then it should change for sub class also

l.name ="new land"
puts f.name # => "land"

what expected is puts f.name # => "new land"

2 Answers 2

2

It seems to me that this is not actually inheritance in the OO sense. If you change Forest so that it holds a reference to the Land then you will get the behavior you wanted.

class Forest
  attr_accessor :rain_level

  def name
    @land.name
  end

  def initialize(land, rain_level)
    @land = land
    @rain_level = rain_level
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

yes, it can achieved without inheritance. How can approach it in inheritance way?. like father can set and get value and son only get the value
Inheritance just doesn't work that way. If you shave the mustache of your father it doesn't mean that your upper lip will also be shaved.
i understand, i expect something like if my father changes his address then my address should change automatically. If my expectation is not a kind of inheritance then please ignore it.
"For example, consider a class Person that contains a person's name, address, phone number, age, gender, and race. We can define a subclass of Person called Student that contains the person's grade point average and classes taken, and another subclass of Person called Employee that contains the person's job-title, employer, and salary." en.wikipedia.org/wiki/Inheritance_(computer_science)
0

This is kind of an interesting thing you want to build.

Summarizing you want to have two objects that share a value but only one is allowed to edit the value, the other one is only allowed to read it.

I think the easiest way to implement this is in your case to implement a new getter in Forest which returns land.name. By writing l.name = 'meow' will f.name return moew too because it holds a reference to l.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.