하위 클래스
Coddy Ruby 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 22번째.
상속은 기존 클래스를 기반으로 새 클래스를 만듭니다. class Dog < Animal은 Dog을 Animal의 서브클래스로 만들며, Animal은 Dog의 슈퍼클래스입니다. 개는 initialize를 포함하여 동물의 모든 메서드를 가지며, 여기에 Dog이 추가하는 메서드도 가집니다:
class Animal
attr_reader :name
def initialize(name)
@name = name
end
def eat
"#{name} is eating"
end
end
class Dog < Animal
def fetch
"#{name} fetches the ball"
end
end
rex = Dog.new("Rex")
puts rex.eat
puts rex.fetch출력:
Rex is eating
Rex fetches the ball추가된 메서드는 서브클래스에만 속합니다. 일반적인 Animal에는 이러한 메서드가 없으며, Cat과 같은 형제 클래스는 Dog의 메서드를 볼 수 없습니다:
class Animal
def breathe
"breathing"
end
end
class Dog < Animal
def fetch
"fetching"
end
end
class Cat < Animal
end
puts Cat.new.breathe
begin
Cat.new.fetch
rescue NoMethodError => e
puts e.message
end출력:
breathing
undefined method `fetch' for an instance of Catsuperclass는 클래스의 부모를 나타냅니다. Ruby 클래스에는 정확히 하나의 슈퍼클래스가 있으며, < 없이 선언된 클래스는 Object를 상속합니다. Object는 모든 객체에 to_s 및 inspect와 같은 메서드를 제공합니다.
class Animal
end
class Dog < Animal
end
puts Dog.superclass
puts Animal.superclass
puts Object.superclass출력:
Animal
Object
BasicObject상속은 is-a 관계에 해당합니다. 개는 동물이고, 저축 계좌는 계좌입니다. 공통 동작은 슈퍼클래스에 한 번만 넣고, 각 서브클래스는 자신을 다르게 만드는 요소를 추가합니다. 이 섹션에서는 각 클래스가 자체 파일에 있으며, 슈퍼클래스의 파일이 먼저 로드됩니다:
# main.rb
require_relative 'animal' # 슈퍼클래스를 먼저
require_relative 'dog' # class Dog < Animal은 Animal이 필요함
require_relative 'cat'챌린지
쉬움클래스를 완성하세요. Vehicle은 name과 wheels의 개수를 저장하며, Mini has 4 wheels를 반환하는 describe를 가집니다. Car와 Bike는 Vehicle의 서브클래스이며 initialize를 정의하지 않습니다. Car는 Mini says beep를 반환하는 honk를 추가하고, Bike는 BMX rings를 반환하는 ring을 추가합니다.
제공된 코드는 car Mini 또는 bike BMX 행을 읽고, 바퀴가 4개인 Car 또는 바퀴가 2개인 Bike를 생성한 다음 describe, 소리(honk 또는 ring), 그리고 객체 클래스의 슈퍼클래스를 출력합니다.
코드는 vehicle.rb, car.rb 및 bike.rb에 작성합니다. main.rb에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
require_relative 'vehicle'
require_relative 'car'
require_relative 'bike'
# 제공된 입력/출력 코드: 그대로 유지하세요
input = []
while (line = gets)
input << line.chomp
end
input.each do |line|
kind, name = line.split(" ", 2)
if kind == "car"
v = Car.new(name, 4)
sound = v.honk
else
v = Bike.new(name, 2)
sound = v.ring
end
puts v.describe
puts sound
puts v.class.superclass
end
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러