34,333
edits
Changes
no edit summary
Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the ''methods'' will do and what the ''member'' variables will be.
New classes can be created based on existing classes, a concept known as ''inheritance''. In such a scenario the new class (known as the ''subclass'') inherits all the features of the parent class (known as the ''superclass'') with added features that differentiate it from the ''superclass''. Ruby support supports ''single inheritance'' in that a subclass can only inherit from a single ''superclass''.
Other languages such as Java support ''multiple inheritance'' where the ''subclass'' can inherit the characteristics of multiple superclasses.
== Defining a Ruby Class ==
For the purposes of this tutorial we will create a new class intended to be used as part of a banking application. Classes are defined using the ''class'' keyword followed by the ''end'' keyword and must be given a name by which they can be referredreferenced. This name is a constant so must begin with a capital letter.
With these rules in mind we can begin work on our class definition:
</pre>
This creates an a BankAccount object named ''account''. Having created the object we can call our test_method:
<pre>
== Instance Variables and Accessor Methods ==
Instance variables are variables defined in a class that are available only to each instance of the class. Instance variables may be defined either inside or outside of class methods. To make the varaibles variables available from outside the class, they must be defined within ''accessor methods'' (also known as a getter method).
For example, we might want to add instance variables to our ''BankAccount'' class:
</pre>
The two ''puts'' statements above will print out the values of the two variables returned by athe the accessor methods (in this case "12345" and "John Smith" respectively).
Now that we can "get" the value of an instance variable, we now need a way to "set" the value of an instance variable. One way to do this is via a ''setter'' methods. Let's clean up our BankAccount class, so that it has two instance variables with getters and setters:
== Ruby Class Inheritance ==
As we mentioned earlier in this chapter, Ruby supports ''single inheritance''. This means that a subclass can be created which that inherits all the variables and methods of another class. The subclass is then extended to add new methods or variables not available in the superclass.
One class inherits from another using the < character. Say, for example, that we want a new kind of BankAccount class. This class needs all the same variables and methods as our original class, but also needs the customer's phone number. To do this we simply inherit from ''BankAccount'' and add the new instance variable: