Part 09 - Methods
| Definition: Method A function exclusively associated with a |
Defining a Method
Methods must be defined in classes. They are declared just like functions are.
Meow!
An object of Cat must be instanced, then its methods can be called.
| Recommendation Names of methods should always be verbs. |
Class Constructor and Destructor
Constructors and Destructors are special methods that are called on when a class is being instanced or destroyed, respectively.
Both are optional.
Whiskers Whiskers is no more... RIP
If a constructor has arguments, then they must be supplied when instancing. Destructors cannot have arguments.
Buttons
| Be Careful Do not depend on the destructor to always be called. |
Method Modifiers
Modifier |
Description |
|---|---|
|
an |
|
a |
|
|
|
All these modifiers also apply to properties (If they are explicitly declared).
static can also apply to fields.
This will cause the Id to increase whenever an Animal is instanced, giving each Animal their own, unique Id.
All the methods defined in an interface are automatically declared abstract.
Abstract methods in a class must have a blank code block in its declaration.
Both declare roughly the same thing.
Member Visibility
Visibility Level |
Description |
|---|---|
|
Member is fully accessible to all types. |
|
Member is only visible to this class and inheriting classes. |
|
Member is only visible to this class. |
| Important Information All fields are by default |
| Recommendation Fields are typically either |
| Recommendation It is recommended you prefix field names with an underscore if it is a private field. |
Declaring Properties in the Constructor
One very nice feature that boo offers is being able to declare the values of properties while they are being instanced.
42
The constructor didn't take any arguments, yet the Value: 42 bit declared Value to be 42, all in a tighly compact, but highly readable space.
Exercises
- Create two
classes,PredatorandPrey. To thePredatorclass, add anEatmethod that eats thePrey. Do not let thePreybe eaten twice.


