|
Let's explain the code now
The Family class (the subclass) is created using elements from the Font class itself.The constructor accepts arguments for both size and family of the font.The size is controlled by the Font class so in order to make that "reference" correctly and show the program where it needs to go in order to find the size value, we used the "super" method in order to pass the size argument to the constructor of the base class, the Font class (the super class), the one upon which the Family class has just been created.
We then added a "showfamily" method that returns the font family. The "showsize" method is inherited from the super class Font.
Access levels
Access levels to objects inside a class have been introduced due to security reasons.Just imagine the mess a piece of code outside the class could cause if it were able to modify elements within a class.
Restricted access provided by private or protected levels is also used for "hiding" key methods inside your class, usually the methods that ensure the core functionality of the program your coding and that you don't want to be alterable by any means from outside.
In order to prevent such nightmares from happening, modern object oriented programming languages have introduced levels of access for methods:
Public methods — can be accessed from outside the class itself; this can also be interpreted as "allowing" outside code to know your class's internal structure and variable names.
Protected methods - can be called only from inside the class or by objects belonging to classes related by inheritance.
Private methods - can only be called from inside the current object.
Along with each level of access, access modifiers are created(just a fancy name, don't get too scared), corresponding to each level:public,protected and private.
Default access modifier is public, no need to explicitly include it in the code, so you only need to substitute with another one when you need either protected or private modifiers.
In case you've seen at least once a definition of a class in C++ with public and private methods, you'll realize the syntax is much alike, you use the keyword "public", "private" or "protected" followed by the def statement for the method:
class Font
def initialize(size)
@size = size
end
public
def showsize
return @size
end
private
def showfamily
return "serif"
end
end
It's pretty easy to understand the code above: the showsize method is set as public explicitly, and the showfamily is set as private, because this is not a feature that you want to allow to be modified. You want to use only serif fonts and don't want the user to have the option of modifying the font family.
Let's see what happens if we try to even display the font family.
As you can see we're not even allowed to access it directly.
|