类和对象:
定义类:
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "Hi, I'm #{@name} and I'm #{@age} years old."
end
end
创建对象:
person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)
person1.introduce
person2.introduce
继承:
class Student < Person
def initialize(name, age, student_id)
super(name, age)
@student_id = student_id
end
def study
puts "Studying hard with student ID #{@student_id}."
end
end
封装:
class BankAccount
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
@balance -= amount if amount <= @balance
end
def balance
@balance
end
end
多态:
class Shape
def draw
raise NotImplementedError, "Subclasses must implement the draw method."
end
end
class Circle < Shape
def draw
puts "Drawing a circle."
end
end
class Square < Shape
def draw
puts "Drawing a square."
end
end
circle = Circle.new
square = Square.new
circle.draw
square.draw
模块:
module Movable
def move
puts "Moving to a new location."
end
end
class Car
include Movable
end
class Plane
include Movable
end
car = Car.new
plane = Plane.new
car.move
plane.move
抽象类与接口:
class AbstractShape
def area
raise NotImplementedError, "Subclasses must implement the area method."
end
end
class Circle < AbstractShape
def initialize(radius)
@radius = radius
end
def area
Math::PI * @radius**2
end
end
这些例子涵盖了Ruby中面向对象编程的基本概念,包括类的定义、对象的创建、继承、封装、多态、模块以及抽象类与接口等。通过深入理解这些概念,你可以更好地利用Ruby进行面向对象的软件开发。
转载请注明出处:http://www.zyzy.cn/article/detail/6466/Ruby