Inheritance Flashcards
What is inheritance?
Inheritance is when a class inherits behavior from another class. The class that is inheriting behavior is called the subclass and the class it inherits from is called the superclass.
What is ‘super’ and why use it?
super is a built-in function that allows us to call methods up the inheritance hierarchy. When you call super from within a method, it will search the inheritance hierarchy for a method by the same name and then invoke it.
Inheritance vs Modules - when is each one a better choice?
- You can only subclass from one class. But you can mix in as many modules as you’d like.
- If it’s an “is-a” relationship, choose class inheritance. If it’s a “has-a” relationship, choose modules. Example: a dog “is an” animal; a dog “has an” ability to swim.
- You cannot instantiate modules (i.e., no object can be created from a module) Modules are used only for namespacing and grouping common methods together.
What is a method lookup path?
The method lookup path is the order in which classes are inspected when you call a method.
In what order does Ruby look at included modules?
Ruby actually looks at the last module we included first.
This means that in the rare occurrence that the modules we mix in contain a method with the same name, the last module included will be consulted first.
What is namespacing?
Namespacing means organizing similar classes under a module. In other words, we use modules to group related classes.
We call classes in a module by appending the class name to the module name with two colons(::)
buddy = Mammal::Dog.new kitty = Mammal::Cat.new
What is a public method?
A public method is a method that is available to anyone who knows either the class name or the object’s name. These methods are readily available for the rest of the program to use and comprise the class’s interface (that’s how other classes and objects will interact with this class and its objects).
Why use a private method?
Sometimes you’ll have methods that are doing work in the class but don’t need to be available to the rest of the program.
Private methods are only accessible from other methods in the class.
What is a protected method?
A protected method is an in-between approach (not public, and not private), this is used in some less common situations.
In general a protected method:
- from outside the class, acts just like private methods.
- from inside the class, is accessible just like public methods.