Ruby中关于类以及继承的一些知识点

class Point
  VERSION = 2
  @@num = 12
  attr_accessor :x, :y
  def initialize(x, y)
    @x, @y = x, y
  end

  # 1 返回布尔值的方法末位必定要加上?
  # 2 此处的x 与 y 是self.x 的省略写法, 由于有get 方法因此才能够这么写
  # 固然也能够@x @y 这样的写法
  def first_quadrant?
    x > 0 && y > 0
  end

  # 3 可是在给局部变量赋值的时候必定不能简写成 x +=
  def plus(a, b)
    self.x += a
    @y += b
  end

  # 4 符号方法
  # 5 会自动将最后处理出来的结果return出去 此处省略return
  # 6 此处的x 和 y 就是省略了self.x 或者@x 这种写法
  def +(p2)
    Point.new(@x + p2.x, @y + p2.y)
  end

  # 7 此处x 前面不能加self 此处的self指的是类
  def self.second_quadrant?(x , y)
    x < 0 && y > 0
    # self指代的是类
    # print self.xxxx
  end

  # 8 类方法能够合并成多个写法
  class << self
    def foo2
    end
    def bar2
    end
  end

end

# 9 实例没法调用类方法
# 10 类也没法直接调用实例方法

class Point
  # 9 经过类直接调用全局变量 须要给类加一个方法
  # 10 在ruby中能够直接打开类增长你须要的东西
  def self.get_num
    @@num
  end
end

# 11 调用常量
# Point::VERSION

# 12 继承
class Point3D < Point
  # 13 super调用父类的同名方法
  def initialize(x, y, z)
    super(x, y)
    @z = z
  end
end

class Point2D < Point
  # 14 super若是不写参数的话 默认传入全部的参数给super
  def initialize(x, y)
    super
  end
end

# 15 在Ruby中子类能够继承父类的全部方法 无论是private protected public
# 在Ruby子类能够重写如 父类的private 方法但不建议这么作
# 继承最好使用protected 和 public 方法
class Point
  def prv_method
    print 'this is private method'
  end

  private :prv_method

  def pro_metod
    print 'this is protected method'
  end

  protected :pro_metod

  def wat
    prv_method
    pro_metod
  end

  def wut
    # 16 private 方法和 protected最大的区别 private方法不能使用实例调用
    # 只能隐式调用 因此self.prv_method 方法是错误的
    # self.prv_method
    self.pro_metod
  end
end

# 17 is_a? 和 instance_of 的区别
p3 = Point3D.new(1, 2, 3)

# 18 is_a? 只要是这个类的实例或者是子类的实例均可
p p3.is_a?(Point)
p p3.instance_of?(Point3D)

# 19 instance_of? 只能是这个类的实例才能够
p p3.instance_of?(Point)
p p3.instance_of?(Point3D)

# 20 = - p3等于上个计算式的结果
# p1 = Point(2, 3)
# p2 = Point(3, 4)
# p1 + p2
# p3 = -
相关文章
相关标签/搜索