Getting Began With Ruby the Simple Manner Pt9 – OOP Pt3




To date, you’ve realized principally concerning the fundamentals of Ruby and object-oriented programming. Now, it’s time to take your abilities additional and discover extra superior ideas of OOP. On this half, you’ll study inheritance, methodology overriding, tremendous and operator overloading. It will carry you nearer to changing into a Ruby programmer!

Getting Began With Ruby the Simple Manner Part 1 (Feedback, Variables, Strings).

Getting Began With Ruby the Simple Manner Part 2 (Information Sorts Pt1).

Getting Began With Ruby the Simple Manner Part 3 (Information Sorts Pt2, Management Circulation Pt1).

Getting Began With Ruby the Simple Manner Part 4 (Management Circulation Pt2).

Getting Began With Ruby the Simple Manner Part 5 (Management Circulation Pt3).

Getting Began With Ruby the Simple Manner Part 6 (Strategies).

Getting Began With Ruby the Simple Manner Part 7 (Recursion, Scope, OOP Pt1).

Getting Began With Ruby the Simple Manner Part 8 (OOP Pt2).

Getting Began With Ruby the Simple Manner Part 10 (OOP Pt4 and Past).

Ruby and OOP (Object-Oriented Programming) pt3

Inheritance

You understand how to create classes and their instances. Subsequent is inheritance. Inheritance is when one class receives, or inherits, attributes and habits from one other. When this occurs, the category that’s inheriting habits is named a “subclass”, additionally referred to as “derived” class. The category it inherits from is named the “superclass”, additionally referred to as “base” class.

Think about you will have quite a lot of courses. Every of those courses represents some animal. For instance, cat, canine, armadillo, fowl, bear and so forth. All these animals are much less or extra completely different. For instance, a canine can bark whereas cat and armadillo can’t. Fowl can fly whereas bear and canine can’t. Nonetheless, there are nonetheless some attributes and behaviors these animals could share.

For instance, all of them may be alive. All of them have particular coloration and title. You may implement this similarity creating one “superclass” Animal and let all these animals inherit from it, i.e.: make them “subclasses” of Animal “superclass”. This lets you specify these normal attributes and behaviors solely as soon as and use them as you want.

If you wish to inform Ruby that some class ought to inherit from one other class, or be its “subclass”, you utilize the “lower than” image (<). You do that while you declare the category. Which means you utilize the class key phrase, adopted by the title of the “subclass” adopted by < which is then adopted by the title of the “superclass”.

Let’s check out how you possibly can write the instance with animals in Ruby utilizing inheritance. First, you’ll outline the “superclass” Animal. This “superclass” will comprise the attributes and performance you wish to share with its “subclasses”. Then, you’ll outline class for every animal and let it inherit from Animal, turn into its “subclasses”.

##
# Create a superclass Animal
class Animal
  def initialize(title, coloration)
    @title = title
    @coloration = coloration
  finish

  def printInfo
    places "That is #{@title}, and its coloration is #{@coloration}."
  finish
finish

# Create a category Armadillo, make it a subclass of Animal
class Armadillo < Animal
finish

# Create a category Bear, make it a subclass of Animal
class Bear < Animal
finish

# Create a category Fowl, make it a subclass of Animal
class Fowl < Animal
finish

# Create a category Cat, make it a subclass of Animal
class Cat < Animal
finish

# Create a category Canine, make it a subclass of Animal
class Canine < Animal
finish

# Create occasion of Bear class
grizzly = Bear.new("Grizzly", "brown")
grizzly.printInfo
# outputs "That is Grizzly, and its coloration is brown."

# Create occasion of Cat class
akita = Cat.new("Akita", "white")
akita.printInfo
# outputs "That is Akita, and its coloration is white."

Inheritance and extra strategies and attributes

As you possibly can see on the earlier instance, each Bear and Cat can use the attributes and strategies of the Animal class, such because the printInfo methodology. That is true about the remainder of “subclasses” as nicely. Nonetheless, this doesn’t imply that Ruby will now prohibit these subclasses to make use of solely attributes and strategies of their “superclass”.

Each “subclass” can even have its personal strategies and attributes. For instance, you possibly can add one methodology to the subclass Cat that may output “Meow” and one other to the subclass Canine that may output “Woof”. Let’s name each these strategies merely communicate. You are able to do the identical with the remainder of subclasses in order for you, and if you determine what “noise” armadillo, bear and fowl do.

##
# Superclass Animal
class Animal
  def initialize(title, coloration)
    @title = title
    @coloration = coloration
  finish

  def printInfo
    places "That is #{@title}, and its coloration is #{@coloration}."
  finish

  def communicate
    places "Roar!"
  finish
finish

# Subclass Cat
class Cat < Animal
  attr_accessor :age

  def communicate
    places "Meow."
  finish
finish

# Create occasion of Cat class
akita = Cat.new("Lucy", "white")
akita.age = 1

akita.printInfo
# outputs "That is Lucy, and its coloration is white."

# Output Lucy's age
places akita.age
# outputs "1"

akita.communicate
# outputs "Meow."

# Subclass Canine
class Canine < Animal
  attr_accessor :age

  def communicate
    places "Woof!"
  finish
finish

# Create occasion of Canine class
husky = Canine.new("Max", "black")
husky.age = 3

husky.printInfo
# outputs "That is Max, and its coloration is black."

# Output Max's age
places husky.age
# outputs "3"

husky.communicate
# outputs "Woof!"

Technique overriding

Within the earlier instance, each Cat and Canine inherit from Animal. And, they each even have their very own occasion variable age and communicate methodology. As you most likely observed, the Animal superclass additionally has its personal communicate methodology. Nonetheless, while you name this methodology on the akita and husky situations, the output you get is the output laid out in Cat and Canine subclasses.

In Ruby, that is referred to as “methodology overriding”. Put merely, because of this methodology outlined in a “subclass” overrides, or replaces, the unique methodology outlined within the “superclass”. In our instance, communicate methodology in Cat and Canine subclasses overrides the communicate methodology within the Animal superclass.

So, for this reason while you referred to as communicate methodology on the akita and husky you get completely different output. Nonetheless, for those who attempt to name this methodology on occasion of Armadillo, Bear or Fowl, you’ll get the output you laid out in Animal superclass. These subclasses didn’t override the strategy.

##
# Superclass Animal
class Animal
  def initialize(title, coloration)
    @title = title
    @coloration = coloration
  finish

  def printInfo
    places "That is #{@title}, and its coloration is #{@coloration}."
  finish

  def communicate
    places "Roar!"
  finish
finish

# Class Armadillo
class Armadillo < Animal
finish

# Class Bear
class Bear < Animal
  attr_accessor :age
finish

# Create occasion of Bear class
grizzly = Bear.new("Grizzly", "brown")
grizzly.age = 6

places grizzly.age
# outputs 6

grizzly.communicate
# outputs "Roar!"

# Create occasion of Cat class
marley = Armadillo.new("Marley", "grey")

marley.communicate
# outputs "Roar!"

Inheritance on a number of ranges

Inheritance is an effective way to take away duplicates in your code. You may write the shared, or normal, performance and attributes within the “superclass” after which implement extra performance in particular subclass while you want it. This might help you retain your code easy, clear, succinct and maintainable.

As well as, you possibly can take the idea of inheritance one step additional. Ruby lets you have a number of ranges of inheritance. For instance, you possibly can create a superclass Animal. Then, you possibly can create new courses Fowl, Fish, Mammal and Reptile as its subclasses. Lastly, you possibly can create one other courses as subclasses of those subclasses.

# Superclass Animal
class Animal
finish

# Class Fowl, subclass of Animal
class Fowl < Animal
finish

# Class Fish, subclass of Animal
class Fish < Animal
finish

# Class Mammal, subclass of Animal
class Mammal < Animal
finish

# Class Reptile, subclass of Animal
class Reptile < Animal
finish

# Class Canine, subclass of Mammal
class Canine < Mammal
finish

# Class Cat, subclass of Mammal
class Cat < Mammal
finish

# Class Snake, subclass of Reptile
class Snake < Reptile
finish

# Class Turtle, subclass of Reptile
class Turtle < Reptile
finish

Within the code above, the Turtle and Snake courses inherits from class Reptile which inherits from Animal. This may be additionally described as an “is a” (or “is an”) relationship. Which means, a Turtle is a Reptile, which “is an” Animal. That is an instance of a single inheritance with a number of ranges of hierarchy. With regards to inheritance, there’s mainly no restrict in Ruby to how lengthy this “inheritance chain” may be. So, it is just as much as you what you think about to be excessive and what not.

Nonetheless, there’s one factor Ruby won’t permit. Ruby doesn’t help a number of inheritance. Which means one class can’t inherit from a number of courses concurrently. In different phrases, class can’t have a number of superclasses. Nonetheless, there’s a technique to obtain this in Ruby. It’s through the use of “mixins”. You’ll study mixins within the next part.

Tremendous

One other factor that may be helpful is Ruby built-in methodology referred to as “tremendous”. If you use “tremendous” in a way of the subclass, the strategy of the identical title will get referred to as from the superclass. For instance, within the code instance with Animal superclass you used methodology overriding to alter the communicate methodology in its subclasses.

With “tremendous” you possibly can first name the “authentic” communicate methodology from the Animal superclass. Then, you possibly can name the “new” communicate methodology in from the subclass. To do that, add the tremendous into the block of code inside communicate methodology, above the brand new places assertion. That is additionally the way you inform Ruby what methodology you wish to name with “tremendous”.

You add the “tremendous” into the strategy with the identical title. Ruby will then discover the strategy with this title within the superclass and name it. Again to the Animal. Now, for those who create a brand new occasion of sophistication Canine, and name its communicate methodology, you’ll get each, “Roar!” kind the “authentic” communicate and “Woof!” from the “new” communicate.

# Superclass Animal
class Animal
  def communicate
    places "Roar!"
  finish
finish

# Subclass Canine
class Canine < Animal
  def communicate
    # Add tremendous to name communicate from Animal superclass
    tremendous

    # new places assertion
    places "Woof!"
  finish
finish

rex = Canine.new

# Name communicate methodology on rex
rex.communicate
# Outputs:
# Roar!
# Woof!

Amongst Ruby developers, “tremendous” is extra usually used within the initialize methodology. Let’s say that you’ve a superclass. This superclass has a initialize methodology that takes one argument and initializes an occasion variable, say, @title. Subsequent, you will have a subclass. This subclass additionally must have its personal occasion variable, say, @age.

This implies that you will want to outline new initialize methodology for this subclass. The issue is that the subclass wants each occasion variables, @title and @age. Now, you will have two choices. First, you possibly can copy the initialize methodology from the superclass and create its duplicate within the subclass, and add @age occasion variable.

The second choice is to make use of “tremendous”. Which means, as an alternative of repeating the entire initialize methodology, and setting the @title occasion variable within the subclass, you should utilize initialize from the superclass and add the brand new @age occasion variable. Do not forget that if the “authentic” initialize takes the variable as a parameter, you will need to additionally embrace it while you declare new initialize and while you use “tremendous”.

# Superclass Animal
class Animal
  # Unique "initialize" methodology with occasion variable "@title"
  def initialize(title)
    @title = title
  finish
finish

# Subclass Cat
class Cat  < Animal
  # New "initialize" methodology with occasion variable "@age"
  def initialize(title, age)
    # Utilizing the "title" as parameter for "tremendous" (required by th authentic initialize methodology)
    tremendous(title)

    # Extra occasion variable for subclass Cat
    @age = age
  finish

  def printInfo
    places "Cat #{@title} is #{@age} years previous."
  finish
finish

cindy = Cat.new("Cindy", 3)
cindy.printInfo
# Outputs: Cat Cindy is 3 years previous.

Operator overloading

Think about a state of affairs the place you’d wish to add collectively two situations, or objects, and create new one. Luckily, Ruby lets you use one thing referred to as “operator overloading”. As you understand, all the things in Ruby is an object. This is applicable additionally to operators, akin to +, -, * and /. In a reality, all these operators are strategies.

You may outline and redefine strategies. Since operators are simply one other bunch of built-in Ruby strategies, you possibly can outline and redefine them as nicely. Which means Ruby lets you do issues akin to including two objects collectively. Let’s say you will have a category Form. This object has two properties, width and top.

What you need is to mix two Form objects in a method that you’ll get a brand new object. This new object can have the width and top equal to the sum of the width and top properties of the 2 objects you mixed. All it is advisable do to attain this result’s to outline the proper operator, the + on this case, as a way.

# Class Form
class Form
  attr_accessor :top, :width

  def initialize(top, width)
    self.top = top
    self.width = width
  finish

  # The "+" methodology that may permit to mix two objects.
  # The "self" is the present, first, object and the "different" is the second.
  def +(different)
    Form.new(self.top + different.top, self.width + different.width)
  finish
finish

# Create first two situations of Form
shapeX = Form.new(3, 7)
shapeY = Form.new(12, 11)

# Mix the earlier situations of Form to create new one
shapeZ = shapeX + shapeY

places shapeZ.top
# Outputs: 15 (3 + 12)

places shapeZ.width
# Outputs: 18 (7 + 11)

Epilogue: Getting Began With Ruby the Simple Manner Pt9

Congratulations! You’ve simply completed one other a part of Getting began with Ruby sequence. Right now, you’ve made large progress in your journey to study Ruby. A big a part of object-oriented programming is not a thriller for you. You may outline new courses and their situations with confidence and obtain what do you want.

By now, you additionally know what’s inheritance and the best way to use it to create superclasses and subclasses. You additionally know the best way to use methodology overriding and tremendous while you want. Lastly, you additionally know that bizarre factor referred to as “operator overloading”, in addition to the best way to use it. This implies writing extra highly effective, but additionally cleaner and maintainable code in Ruby.

Within the next part, you’ll study ideas akin to entry modifiers and to_s methodology. It will make your journey to the world of Ruby and object-oriented programming full. Subsequent, you’ll study modules, mixins and different attention-grabbing issues Ruby has to supply. For now, apply what you’ve realized at this time.

If you happen to preferred this text, please subscribe so you do not miss any future publish.








If you would like to help me and this weblog, you possibly can turn into a patron, or you should purchase me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Began #Ruby #Simple #Pt9 #OOP #Pt3