티스토리 뷰

Ruby & Rails

Ruby 처음 배우기 : 상속

조묵헌 2018. 5. 11. 12:36

루비에서의 상속

상속 문법

is-a 관계 : 예를들어, Cat is-a Animal의 관계가 성립할 때 상속을 사용합니다. 상속은 < 키워드를 사용하여 표현합니다.

루비에서는 클래스 정의 시에 슈퍼클래스를 지정하지 않으면 자동으로 Object 클래스를 상속받습니다.

루비에서 클래스는 단 하나의 부모클래스만 가질 수 있습니다.

# 부모 클래스
class Animal
  def eat
    puts "Eating!"
  end
end

# 자식 클래스
class Cat < Animal
end

cheshire_cat = Cat.new
cheshire_cat.eat

상속받은 클래스를 확인하기

# superclass 확인하기
Animal.superclass        #=> Object
Cat.superclass        #=> Animal

Override

자식클래스에서 부모클래스의 속성이나 메서드를 대체합니다.

class Animal
  def initialize(name)
    @name = name
  end

  def walk
    return "Walking"
  end
end

# 메서드 Override
class Dog < Animal
  def walk
    return "Dog Walking!"
  end
end

super 키워드를 사용하면, 자식 클래스(sub, derived) 에서 부모 클래스(super, base) 의 속성이나 메소드에 직접 액세스 할 수 있습니다.

# super 문법
class DerivedClass < Base
  def some_method
    super(optional args)
      # Some stuff
    end
  end
end

Public & Private Method

메소드는 기본적으로 public메서드 입니다. private 키워드를 사용해 private 메서드를 생성하며, private 메서드는 class 외부에서 접근할 수 없습니다.

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  public
  def bark
    puts "bow!"
  end

  private
  def id
    @id_number = 42
  end
end

'Ruby & Rails' 카테고리의 다른 글

Ruby 처음 배우기 : Mixin  (0) 2018.05.11
Ruby 처음 배우기 : Module  (0) 2018.05.11
Ruby 처음 배우기 : Class  (0) 2018.05.11
Ruby 처음 배우기 : Block & Yield  (0) 2018.05.10
Ruby 처음 배우기 : 메서드  (0) 2018.05.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함