ruby 笔记之五

本文通过具体的Ruby代码示例,展示了如何实现类的继承、实例变量、类变量、类方法及静态类等面向对象编程概念,并介绍了实例方法的覆盖。

1.

class Person
  def initialize
    puts "nijhao"
  end
  def talk (name)
    puts "your name is #{name} "
  end   
end


=begin

p = Person.new
p.talk("samba")
=end
class Student < Person
  
  def talk (name)
    super
    puts "your name is #{name}"
  end   
end


p1 = Person.new

p1.talk("gjhohj")

p2 = Student.new
p2.talk("samba")

 

2.

#实例变量、类变量、类方法

#与全局变量和实例变量不同,类变量在使用前必须要初始化;全局变量和实例变量如果没有初始化,其值为 nil 。

class Student
 
  @@count = 0 ;  #类变量
  def initialize(name)
    @name = name
    @@count += 1
  end
 
  def talk
    puts   "name=  #@name,this is class count  #@@count"
  end
 
 
end


p = Student.new("samba")

p1 = Student.new("gjhohj")


p1.talk

p.talk

3.

#static class

class Student
 
  @@count = 0
   def initialize
     @@count += 1
   end
  
   def Student.classCount
     puts "class's count  #@@count"
   end
  
  
 end
 
 p = Student.new
 p1 = Student.new
 
 Student.classCount
 
 
4.

#实例方法

class Person
 
  def talk
    puts "hello" 
  end
 
end

p1 = Person.new

p2 = Person.new

def p2.talk
   puts "ps hello" 
end

def p2.laugh
  puts "he he he!!!!"
end

p1.talk

p2.talk

p2.laugh

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值