• Ruby笔记三(类、对象、属性)


    class Person
      #initialize是初始化方法,相当于Java的构造器。参数age有一个缺省值18,
      #可以在任何方法内使用缺省参数,而不仅仅是initialize。如果有缺省参数,参数表必须以有缺省值的参数
    结束  
      def initialize( name, age=18 )
        @name = name
        @age = age
        @motherland = "China"
      end #初始化方法结束
      
      def talk
        puts "my name is "+@name+", age is "+@age.to_s  #@age.to_s:将数@age转换为字符串。
        if @motherland == "China"
          puts "I am a Chinese."
        else
          puts "I am a foreigner."
        end
      end # talk方法结束
      attr_writer :motherland
    =begin
    attr_writer :motherland 相当于
    def motherland=(value)
      return @motherland =value
    end

    attr_ reader :motherland 相当于
    def motherland
      return @motherland
    end  

    attr_accessor :motherland 相当于
    attr_reader:motherland;attr_writer :motherland
    =end  
    end # Person类结束

     class Student < Person
      def talk
        puts "I am a student. my name is "+@name+", age is "+@age.to_s
      end # talk方法结束
    end # Student类结束

    p1=Person.new("kaichuan",20)
    p1.talk #my name is kaichuan, age is 20 I am a Chinese.

    p2=Person.new("Ben")
    p2.motherland="ABC"
    p2.talk #my name is Ben, age is 18 I am a foreigner.
    p3=Student.new("kaichuan",25)
    p3.talk #I am a student. my name is kaichuan, age is 25

    p4=Student.new("Ben")
    p4.talk #I am a student. my name is Ben, age is 18
  • 相关阅读:
    使用iframe从网页调起移动端应用
    综合练习:词频统计
    组合数据类型练习
    python 绘制五星红旗
    熟悉常用的Linux操作
    大数据概述
    windowBackground打造闪屏页
    安卓日期选择对话框
    c语言语法分析器
    C语言文法
  • 原文地址:https://www.cnblogs.com/jeriffe/p/2333072.html
Copyright © 2020-2023  润新知