- Objects
- Classes
- Members and Scope
- Properties
- Methods and Behavior
- Events and Delegates
- Constructors
- Destructors
- Interfaces
- Summary
- Q&A
- Workshop
Methods and Behavior
The behavior of an object is defined by its methods, which are the functions and subroutines defined within the object class. Without class methods, a class would simply be a structure.
Methods determine what type of functionality a class has, how it modifies its data, and its overall behavior. Methods go beyond what properties do for an object, in that they aren't bound by a rigid implementation guideline and aren't tied to a member data item. They can be subroutines or functions and declared as public, protected, or private.
A class that inherits another class can also override methods of the inherited class to enhance or change its behavior. If the new class changes a method's behavior, it overrides the method and doesn't call the base class's method, as shown in the following:
Class DrawName Public Overridable Sub Draw() System.Console.WriteLine("Nobody") End Sub End Class Class DrawMyName Inherits DrawName Public Overrides Sub Draw() System.Console.WriteLine("John Doe") End Sub End Class
The preceding example shows how overriding the Draw() method can change the results the class produces when the Draw() method is called. The next example shows how overriding the Draw() method can enhance the results the class produces when the Draw() method is called:
Class DrawName Public Overridable Sub Draw() System.Console.WriteLine("What is your name?") End Sub End Class Class DrawMyName Inherits DrawName Public Overrides Sub Draw() MyBase.Draw() System.Console.WriteLine("John Doe") End Sub End Class
When you override the Draw() method, which then calls the MyBase.Draw() method to avoid losing the functionality provided by the base class DrawName, the new class enhances or adds to the behavior of the base class.