Friday, February 03, 2006
Introduction To Patterns - Architecting Your Football Engine
Contents
- Part I
- Part II
Part
I
Solution Architect: "But you can use patterns"
Dumb Developer: "Yes, But can I get it as an ActiveX control?"
Introduction
Introduction To This Article
This article is expected to
- Introduce patterns to you in a simple, human readable (?) way
- Train you how to really 'Apply' patterns (you can learn patterns easily, but to apply them to solve a problem, you need real design skills)
- Provide you a fair idea regarding the contexts for applying the following patterns - Builder, Observer, Strategy and Decorator (well, they are few popular design patterns)
- Demonstrate you how to apply the Observer pattern, to solve a design problem
In this entire article, you will go through the following steps
- You will model a very simple football game engine
- You will identify the design problems in your football game engine
- You will decide which patterns to use for solving your design problems
- You will then actually use the observer pattern, to solve one of your design problem.
As a prerequisite
- You may need to get some grip on reading and understanding UML diagrams
Using The Code
- The related zip file includes the code, UML designs (in Visio format) etc. After reading this article, you may download and extract the zip file - using a program like Winzip - to play with the source code.
An Overview Of Design Patterns
Even with out much knowledge about design patterns, designers and developers tend to reuse class relationships and object collaborations to simplify the design process. In short, "A Design pattern consists of various co-operating objects (classes, relationships etc)". They provide solutions for common design problems. More than anything else, they offer a consistent idiom for designers and programmers to speak about their design. For example, you can tell a friend that you used a 'Builder' pattern for addressing some design specifications in your project.
A consistent classification of patterns for common design problems are provided by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides [also known as the Gang of Four (GOF)]. The Gang of Four (GOF) patterns are generally considered the foundation for all other patterns.
The basic principle of using patterns is reusability. Once a problem is address some way, you are not really expected to re-invent the wheel if you properly understand the concept of pattern centric software engineering. Here are some important points to remember about design patterns.
- A Design Pattern is not code. It is in fact an approach or a model that can be used to solve a problem.
- Design Patterns are about design and interaction of objects and they provide reusable solutions for solving common design problems.
- A Design Pattern is normally represented with the help of a UML diagram.
Some real hands on experience with patterns may provide you a better idea!!
Architecting Your (Simple) Football Engine
You are working with a popular computer game developing company, and they made you the Solution Architect of one of their major projects - a Soccer (Football) Game Engine (Nice, huh?). Now, you are leading the process of designing the entire Football game engine, and suddenly you have a lot of design considerations, straight away. Let us see
- How you identify the entities in your game system,
- How you identify the design problems, and
- How you apply patterns to address your design specifications.
Identifying Entities
First of all, you need to identify the objects you use in your game engine. For this, you should visualize how the end user is going to use the system. Let us assume that the end user is going to operate the game in the following sequence (let us keep things simple).
- Start the game
- Select two teams
- Add or remove players to/from a team
- Pick a play ground
- Start the game
Your system may have a number of PlayGrounds in it, a number of Teams etc. To list a few real world objects in the system, you have
- Player who play the soccer
- Team with various players in it
- Ball which is handled by various players.
- PlayGround where the match takes place.
- Referee in the ground to control the game.
Also, you may need some logical objects in your game engine, like
- Game which defines a football game, which constitutes teams, ball, referee, playground etc
- GameEngine to simulate a number of games at a time.
- TeamStrategy to decide a team's strategy while playing
So, here is a very abstract view of the system. The boxes represent classes in your system, and the connectors depicts 'has' relationships and their multiplicity. The arrow head represents the direction of reading. I.e, a GameEngine has (can simulate) Games. A Game has (consists of) three referees, one ball, two teams, and one ground. A team can have multiple players, and one strategy at a time.

Fig 1 - High level view
Identifying Design Problems
Now, you should decide
- How these objects are structured
- How they are created
- Their behavior when they interact each other, to formulate the design specifications.
First of all, you have to write down a minimum description of your soccer engine, to identify the design problems. For example, here are few design problems related to some of the objects we identified earlier.
- Ball
- When the position of a ball changes, all the players and the referee should be notified straight away.
- Team and TeamStrategy
- When the game is in progress, the end user can change the strategy of his team (E.g., From Attack to Defend)
- Player
- A player in a team should have additional responsibilities, like Forward, Defender etc, that can be assigned during the runtime.
- PlayGround
- Each ground constitutes of gallery, ground surface, audience, etc - and each ground has a different appearance.
So now, let us see how to identify the patterns, to address these design problems.
Identifying Patterns To Use
Have a look at the design problems you identified above (yes, do it once more). Now, let us see how to address these problems using design patterns.
1: Addressing the design problems related with the 'Ball'
First of all, take the specifications related to the ball. You need to design a framework such that when the state (position) of the ball is changed, all the players and the referee are notified regarding the new state (position) of the ball. Now, let us generalize the problem
Specific Design Problem: "When the position of a ball changes, all the players and the referee should be notified straight away."
Problem Generalized: "When a subject (in this case, the ball) changes, all its dependents (in this case, the players) are notified and updated automatically."
Once you have such a design problem, you refer the GOF patterns - and suddenly you may find out that you can apply the 'Observer' pattern to solve the problem.
|
|
In this case, we used this pattern because we need to notify all the players, when the position of the ball is changed.
2: Addressing the design problems related with 'Team' And 'TeamStrategy'
Next, we have to address the specifications related to the team and team strategy. As we discussed earlier, when the game is in progress, the end user can change the strategy of his team (E.g., From Attack to Defend). This clearly means that we need to separate the Team's Strategy from the Team that uses it.
Specific Design Problem: "When the game is in progress, the end user can change the strategy of his team (E.g., From Attack to Defend)"
Problem Generalized: "We need to let the algorithm (TeamStrategy) vary independently from clients (in this case, the Team) that use it."
Then, you can chose the 'Strategy' pattern to address the above design problem.
|
|
3: Addressing the design problems related with 'Player'
Now, let us address the design specifications related to the player. From our problem definition, it is clear that we need to assign responsibilities (like forward, defender etc) to each player during run time. At this point, you can think about sub classing (i.e, inheritance) - by creating a player class, and then inheriting classes like Forward, Defender etc from the base class. But the disadvantage is that, when you do sub classing, you cannot separate the responsibility of an object from its implementation.
I.e, In our case, sub classing is not the suitable method, because we need to separate the responsibilities like 'Forward', 'Midfielder', 'Defender' etc from the Player implementation. Because, a player can be a 'Forward' one time, and some other time, the same player can be a 'Midfielder'.
Specific Design Problem: "A player in a team should have additional responsibilities, like Forward, Defender etc, that can be assigned during the runtime."
Problem Generalized: "We need to attach additional responsibilities (like Forward, Midfielder etc) to the object (In this case, the Player) dynamically, with out using sub classing"
Then, you can chose the 'Decorator' pattern to address the above design problem.
|
|
4: Addressing the design problems related with 'PlayGround'
If you take a look at the specifications of Ground, we see that a ground's appearance is decided by various sub units like gallery, surface of the ground, audience etc. The appearance of the ground may vary, according to these sub units. Hence, we need to construct the ground in such a way that, the construction of the ground can create different representations of the ground. I.e, a ground in Italy may have different gallery structure and surface when compared to a ground in England. But, the game engine may create both these grounds by calling the same set of functions.
Specific Design Problem: "Each ground constitutes of gallery, ground surface, audience, etc - and each ground has a different appearance."
Problem Generalized: "We need to separate the construction of an object (ground) from its representation (the appearance of the ground) and we need to use the same construction process to create different representations."
|
|
Now, you can chose the 'Builder' pattern to address the above design problem.
Part
II
Solution Architect: "I asked you to learn about patterns"
Dumb Developer: "Yes, now I can develop a football engine using patterns"
Solution Architect: "Huh? What do you mean? !@@#!"
Applying Observer Pattern
In this section, we will have a closer look at the observer pattern, and then we will apply the pattern to solve our first design problem. If you can remember, our first design problem was,
- "When the position of a ball changes, all the players should be notified straight away."
Understanding the Observer Pattern
The UML class diagram of the observer pattern is shown below.

Fig 2 - Observer Pattern
The participants of the pattern are detailed below.
- Subject
This class provides an interface for attaching and detaching observers. Subject class also holds a private list of observers. Functions in Subject class are
- Attach - To add a new observer to the list of observers observing the subject
- Detach - To remove an observer from the list of observers observing the subject
- Notify- To notify each observer by calling the Update() function in the observer, when a change occurs.
- ConcreteSubject
This class provides the state of interest to observers. It also sends a notification to all observers, by calling the Notify function in its super class (i.e, in the Subject class). Functions in ConcreteSubject class are
- GetState - Returns the state of the subject
- Observer
This class defines an updating interface for all observers, to receive update notification from the subject. The Observer class is used as an abstract class to implement concrete observers
- Update - This function is an abstract function, and concrete observers will over ride this function
- ConcreteObserver
This class maintains a reference with the subject, to receive the state of the subject when a notification is received.
- Update - This is the overridden function in the concrete class. When this function is called by the subject, the ConcreteObserver calls the GetState() function of the subject to update the information it have about the subject's state.
Adapting the Observer Pattern
Now, let us see how this pattern can be adapted to solve our specific problem. This will give you a better idea.

Fig 3 - Solving Our First Design Problem
When we call the SetBallPosition function of the ball to set the new position, it inturn calls the Notify function defined in the Ball class. The Notify function iterates all observers in the list, and invokes the Update function in each of them. When the Update function is invoked, the observers will obtain the new state position of the ball, by calling the GetBallPosition function in the Foot ball class.
The participants are detailed below.
Ball (Subject)
The implementation of Ball class is shown below.
' Subject : The Ball Class
Public Class Ball
'A private list of observers
Private observers As new System.Collections.ArrayList
'Routine to attach an observer
Public Sub AttachObserver(ByVal obj As IObserver)
observers.Add(obj)
End Sub
'Routine to remove an observer
Public Sub DetachObserver(ByVal obj As IObserver)
observers.Remove(obj)
End Sub
'Routine to notify all observers
Public Sub NotifyObservers()
Dim o As IObserver
For Each o In observers
o.Update()
Next
End Sub
End Class ' END CLASS DEFINITION Ball
FootBall (ConcreteSubject)
The implementation of FootBall class is shown below.
' ConcreteSubject : The FootBall Class
Public Class FootBall
Inherits Ball
'State: The position of the ball
Private myPosition As Position
'This function will be called by observers to get current position
Public Function GetBallPosition() As Position
Return myPosition
End Function
'Some external client will call this to set the ball's position
Public Function SetBallPosition(ByVal p As Position)
myPosition = p
'Once the position is updated, we have to notify observers
NotifyObservers()
End Function
'Remarks: This can also be implemented as a get/set property
End Class ' END CLASS DEFINITION FootBall
IObserver (Observer)
The implementation of IObserver class is shown below. This class provides interface specifications for creating Concrete Observers.
' Observer: The IObserver Class
'This class is an abstract (MustInherit) class
Public MustInherit Class IObserver
'This method is a mustoverride method
Public MustOverride Sub Update()
End Class ' END CLASS DEFINITION IObserver
Player (ConcreteObserver)
The implementation of Player class is shown below. Player is inherited from IObserver class
' ConcreteObserver: The Player Class
'Player inherits from IObserver, and overrides Update method
Public Class Player
Inherits IObserver
'This variable holds the current state(position) of the ball
Private ballPosition As Position
'A variable to store the name of the player
Private myName As String
'This is a pointer to the ball in the system
Private ball As FootBall
'Update() is called from Notify function, in Ball class
Public Overrides Sub Update ()
ballPosition = ball.GetBallPosition()
System.Console.WriteLine("Player {0} say that the ball is at {1},{2},{3} ", _
myName, ballPosition.X, ballPosition.Y, ballPosition.Z)
End Sub
'A constructor which allows creating a reference to a ball
Public Sub New(ByRef b As FootBall, ByVal playerName As String)
ball = b
myName = playerName
End Sub
End Class ' END CLASS DEFINITION Player
Referee (ConcreteObserver)
The implementation of Referee class is shown below. Referee is also inherited from IObserver class
' ConcreteObserver : The Referee Clas
Public Class Referee
Inherits IObserver
'This variable holds the current state(position) of the ball
Private ballPosition As Position
'This is a pointer to the ball in the system
Private ball As FootBall
'A variable to store the name of the referee
Private myName As String
'Update() is called from Notify function in Ball class
Public Overrides Sub Update()
ballPosition = ball.GetBallPosition()
System.Console.WriteLine("Referee {0} say that the ball is at {1},{2},{3} ", _
myName, ballPosition.X, ballPosition.Y, ballPosition.Z)
End Sub
'A constructor which allows creating a reference to a ball
Public Sub New(ByRef b As FootBall, ByVal refereeName As String)
myName = refereeName
ball = b
End Sub
End Class ' END CLASS DEFINITION Referee
Position Class
Also, we have a position class, to hold the position of the ball.
'Position: This is a data structure to hold the position of the ball
Public Class Position
Public X As Integer
Public Y As Integer
Public Z As Integer
'This is the constructor
Public Sub New(Optional ByVal x As Integer = 0, _
Optional ByVal y As Integer = 0, _
Optional ByVal z As Integer = 0)
Me.X = x
Me.Y = y
Me.Z = Z
End Sub
End Class ' END CLASS DEFINITION Position
Putting It All Together
Now, let us create a ball and few observers. We will also attach these observers to the ball, so that they are notified automatically when the position of the ball changes. The code is pretty self explanatory.
'Let us create a ball and few observers
Public Class GameEngine
Public Shared Sub Main()
'Create our ball (i.e, the ConcreteSubject)
Dim ball As New FootBall()
'Create few players (i.e, ConcreteObservers)
Dim Owen As New Player(ball, "Owen")
Dim Ronaldo As New Player(ball, "Ronaldo")
Dim Rivaldo As New Player(ball, "Rivaldo")
'Create few referees (i.e, ConcreteObservers)
Dim Mike As New Referee(ball, "Mike")
Dim John As New Referee(ball, "John")
'Attach the observers with the ball
ball.AttachObserver(Owen)
ball.AttachObserver(Ronaldo)
ball.AttachObserver(Rivaldo)
ball.AttachObserver(Mike)
ball.AttachObserver(John)
System.Console.WriteLine("After attaching the observers...")
'Update the position of the ball.
'At this point, all the observers should be notified automatically
ball.SetBallPosition(New Position())
'Just write a blank line
System.Console.WriteLine()
'Remove some observers
ball.DetachObserver(Owen)
ball.DetachObserver(John)
System.Console.WriteLine("After detaching Owen and John...")
'Updating the position of ball again
'At this point, all the observers should be notified automatically
ball.SetBallPosition(New Position(10, 10, 30))
'Press any key to continue..
System.Console.Read()
End Sub
End Class
Running the project
After running the project, you'll get the output as

Conclusion
Patterns can be classified
- With respect to purpose.
- With respect to scope.
With respect to purpose, patterns are classified to Creational, Structural and Behavioral. For example,
- The Observer pattern we just learned is a behavioral pattern (because it help us model the behavior and interactions of objects)
- The Builder pattern is a creational pattern (because it details how an object can be created in a particular way) and so on.
Here is the complete classification diagram.
And finally, I hope this article
- May help you to understand how to use design patterns.
- May help you some way to apply patterns in your projects
- May help you to give a brief talk about patterns to your friends :)
And finally, if you have strokes in your head (a sign of great programmers
) - I'll recommend an Art Of Living Part I workshop for you (See http://www.artofliving.org/courses.html ). It is an interactive workshop of 18 hours spread over 6 days. As it did for me, I hope that it may help you to find the right balance between your work and life - to improve the clarity of your mind, and to improve the quality of your life. You can get in touch with them here - http://www.artofliving.org/centers/main.htm
History
- "History may make you realize that life is just a play"
- Nov 07,2005 - Prepared this article for publishing
Introduction To OOP Concepts - Object Oriented Concepts In VB.NET
Contents
- Introduction
- Using the code
- Lesson 1: Namespaces, Classes & Modules
- Lesson 2: Access Types
- Lesson 3: Shared Functions
- Lesson 4: Overloading
- Lesson 5: Inheritance
- Lesson 6: Overriding
- Lesson 7: Polymorphism
- Lesson 8: Constructors & Distructors
- Lesson 9: Property Routines
- Lesson 10: A Simple Application
Introduction
VB.NET is completely Object Oriented. This article uncovers some basic Object Oriented Programming Features of Visual Basic.NET. The whole article is divided to 10 lessons. The source code for these lessons is provided with the article.
This tutorial is designed with the following objectives.
- To provide a sound knowledge about Object Oriented Programming in VB.NET
- To educate how Object Oriented techniques are used in VB.NET
- To explain the following concepts simply and easily.
- Creating And Using Classes And Objects In VB.NET
- Encapsulation, Abstraction, Inheritance And Polymorphism
- Overloading And Overriding
- Constructors And Destructors
- Static Functions
Go through this tutorial and you will start making sense of almost any .NET code. Also, Java/CPP programmers can use this to understand OOPs in VB.NET easily.
Using the code
The source code for each lesson is available as a .vb source code file. You need Microsoft.NET framework SDK installed in your system to compile and execute the excercises in this article. You can download it from the Microsoft website. The VB.NET compiler (vbc.exe) normally resides in your FrameworkSDK\bin folder.
To manually compile a source code file, you may use the command prompt to type
vbc filename.vb /out:"filename.exe" /r:"System.Windows.Forms.dll","System.dll"
Lesson 1: Namespaces, Classes, Objects And Modules
1) A Namespace
In VB.NET, classes and other data structures for a specific purpose are grouped together to form a namespace.You can use the classes in a namespace, by simply importing the namespace.The 'imports' keyword is used to import a namespace to your project..NET framework provides a rich set of built in classes, groupedto various namespaces.In this lesson, we are using the system namespace.Import the System namespace (already available in .NET)Imports System
2) A Class
Probably, you are already familiar with classes and objects. Simply speaking, a class is a definition of a real life object. For example, Human is a class for representing allhuman beings. Dog is a class to represent all Dogs.Classes can contain functions too.Animals is a namespaceNamespace AnimalsDog is a class in the namespace Animals
Class DogBark is a function in this class
Function Bark()
Console.Writeline ("Dog is barking")
End Function
End Class
End Namespace
3) An Object
An object is an instance of a class. For example,Jimmy is an object of type Dog. We will createan object in the next section. Read on.4) Modules
You can use modules to write common functions. A module is agroup of functions. Unlike functions in classes, public functionsin modules can be called directly from some where else.VB provides Functions and Subroutines. Functions and Subroutines are almost same, but subroutines can't returna value.Public Module modMainExecution will start from the Main() subroutine
Sub Main()
'Call our function. See below
OurFunction()
End sub
OurFunction: Our own little function to use the class Dog
Function OurFunction()
'Here is how we declare a variable Jimmy of type Dog.
'We use Animals.Dog because, the class Dog is in the
'namespace Animals (see above).
Dim Jimmy as Animals.Dog
'Create an object. Unlike in VB 6, it is not required to use
'the 'set' keyword.
Jimmy = new Animals.Dog()
'Another way to create an object is
'Dim Jimmy as new Dog
'Call Jimmy's Main Function
Jimmy.Bark()
End Function
End module
Lesson 2: Access Types
The major access types are Public, Private, Friend And Protected.A class may contain functions, variables etc, either publicor private or protected or friend. If they are public,they can be accessed by creating objects of the class.Private and Protected members can be accessed only by functionsinside the class. Protected members are much like private members,but they have some special use while inheriting the class. Wewill see this later, in Inheritance (Lesson 5).Friend members can be accessed only from elements in thesame project, and not by elements outer the current project.Let us expand our dog class.Import the System namespace (already available in .NET)
Imports SystemAnimals is a namespace
Namespace AnimalsDog is a class in the namespace Animals
Public Class Dog 'A public variable Public AgeOfDog as IntegerBark is a function in this class. It is public
Public Function Bark()
Console.Writeline ("Dog is barking")
End Function
Walk is a function in this class. It is private
Private Function Walk()
Console.Writeline ("Dog is walking")
End Function
End Class
End Namespace
Our Module
Public Module modMainExecution will start from the Main() subroutine
Sub Main()
'Call our function. See below
OurFunction()
End sub
'OurFunction: Called from Main()
Function OurFunction()
Dim Jimmy as Animals.Dog
Jimmy=new Animals.Dog()
'This will work, because Bark & Ageofdog are public
Jimmy.Bark
Jimmy.AgeOfDog=10
'Calling the Walk function will not work here, because
'Walk() is outside the class Dog
'So this is wrong. Uncomment this and try to compile, it will
'cause an error.
'Jimmy.Walk
End Function
End Module
Additional Notes:
Encapsulation:
Putting all the data and related functions, in the class is calledas Encapsulation.Data Hiding or Abstraction:
Normally, in a class, variables used to hold data (like the age ofa dog) is declared as private. Functions or property routines are usedto access these variables. Protecting the data of an object fromouter functions is called as Abstraction or Data Hiding. This prevents accidental modification of data by functions outside the class.Lesson 3: Shared Functions
The shared members in a class (both functions and variables)can be used with out creating objects of the class as shown.The Shared modifier indicates the method does not operate on aspecific instance of a type and may be invoked directly froma type rather than through a particular instance of a type.Import the System namespace (already available in .NET)
Imports SystemAnimals is a namespace
Namespace AnimalsDog is a class in the namespace Animals
Class DogBark is a now a public, shared function in this class
Public Shared Function Bark()
Console.Writeline ("Dog is barking")
End Function
Walk is a public function in this class. It is not shared
Public Function Walk()
Console.Writeline ("Dog is walking")
End Function
End Class
End Namespace
Our Module
Public Module modMainExecution will start from the Main() subroutine
Sub Main() 'We can call the Bark() function directly, 'with out creating an object of type Dog - 'because it is shared. Animals.Dog.Bark() 'We can call the Walk() function only 'after creating an object, because 'it is not shared. Dim Jimmy as Animals.Dog Jimmy=new Animals.Dog() Jimmy.Walk() 'Now Guess? The WriteLine() function we used so far 'is a shared function in class Console :) 'Also, we can write the Main() function itself as a shared 'function in a class. i.e Shared Sub Main(). Try 'moving Main() from this module to the above class End sub End Module
Lesson 4: Over Loading
Overloading is a simple technique, to enable a single function name to accept parameters of different type.Let us see a simple Adder class
Import the System namespace (already available in .NET)Imports System Class AdderHere, we have two Add() functions.This one adds two integers.Convert.ToString is equivalent to good old Cstr
Overloads Public Sub Add(A as Integer, B as Integer)
Console.Writeline ("Adding Integers: " + Convert.ToString(a + b))
End Sub
This one adds two strings
Overloads Public Sub Add(A as String, B as String)
Console.Writeline ("Adding Strings: " + a + b)
End Sub
'And both have the same name. This is possible because, we used the
'Overloads keyword, to overload them.
'Here, we have the Main Function with in this class. When you write.
'your main function inside the class, it should be a shared function.
Shared Sub Main()
Dim AdderObj as Adder
'Create the object
AdderObj=new Adder
'This will invoke first function
AdderObj.Add(10,20)
'This will invoke second function
AdderObj.Add("hello"," how are you")
End Sub
End Class
Lesson 5: Inheritance
Inheritance is the property in which, a derived classaquires the attributes of its base class. In simple terms,you can create or 'inherit' your own class (derived class),using an existing class (base class). You can use the Inherits keyword for this.Let us see a simple example.
Import the System namespace (already available in .NET)Imports System
Our simple base class
Class Human
'This is something that all humans do
Public Sub Walk()
Console.Writeline ("Walking")
End Sub
End Class
Now, let us derive a class from human
A programmer IS_A HumanClass Programmer
Inherits Human
'We already have the above Walk() function
'This is something that all programmers do ;)
Public Sub StealCode()
Console.Writeline ("Stealing code")
End Sub
End Class
Just a main class
Class MainClass 'Our main function Shared Sub Main() Dim Tom as Programmer Tom=new Programmer 'This call is okie because programmer got this function 'from its base class Tom.Walk() 'This is also correct because Tom is a programmer Tom.StealCode() End Sub End ClassAdditional Notes:
MustInherit: The MustInherit keyword specifies that a class cannotbe instantiated and can be used only as a base class.i.e, if you declare our Human class as 'MustInherit Class Human' ,then you can't create object of type Human with out inheriting it.
NotInheritable: The NotInheritable keyword specifies that a class cannotbe inherited. I.e, if you specify 'NotInheritable Class Human', noderived classes can be made from Human class
Lesson 6: Overriding
By default, a derived class inherits methods from its base class. If an inherited property or method needs to behave differently inthe derived class it can be overridden; that is, you can define anew implementation of the method in the derived class.The 'Overridable' keyword is used to mark a function as overridable. The keyword 'Overrides' is used to mark that a functionis overriding some base class function.Let us see an exampleImport the System namespace (already available in .NET)
Imports System
Our simple base class
Class Human
'Speak() is declared Overridable
Overridable Public Sub Speak()
Console.Writeline ("Speaking")
End Sub
End Class
Now, let us derive a class from human
An Indian IS_A HumanClass Indian
Inherits Human
'Let us make Indian speak Hindi, the National Language
'in India
'Speak() is overriding Speak() in its base class (Human)
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")
'Important: As you expect, any call to Speak() inside this class
'will invoke the Speak() in this class. If you need to
'call Speak() in base class, you can use MyBase keyword.
'Like this
'Mybase.Speak()
End Sub
End Class
Just a class to put our Main()
Class MainClass 'Our main function Shared Sub Main() 'Tom is a generic Human Dim Tom as Human Tom=new Human 'Tony is a human and an Indian Dim Tony as Indian Tony=new Indian 'This call will invoke the Speak() function 'in class Human Tom.Speak() 'This call will invoke the Speak() function 'in class Indian Tony.Speak() End Sub End Class
Lesson 7: Polymorphism
Polymorphism is the property in which a single object can take more than one forms. For example, if you have a base class named human, an object of human type can be used to hold an object of any of its derved type. When you call a function in your object, the system will automatically determine the type of the object to call the appropriate function. For example, let us assume that you have a function named speak() in your base class. You derived a child class from your base class and overloaded the function speak(). Then, you created a child class object and assigned it to a base class variable. Now, if you call speak() function using the base class variable, the speak() function defined in your child class will work. On the contrary, if you are assigning an object of the base class to the base class variable, the speak() function in base class will work. This is acheived through run time type identification of objects. See the example.Import the System namespace (already available in .NET)
Imports SystemThis example is exactly the same one we saw in previous lesson.The only difference is in the Shared Sub Main() in class MainClass. So scroll down.Let us see an example
Our simple base class
Class Human
'Speak() is declared Overridable
Overridable Public Sub Speak()
Console.Writeline ("Speaking")
End Sub
End Class
Now, let us derive a class from human
An Indian IS_A HumanClass Indian
Inherits Human
'Let us make Indian speak Hindi, the National Language
'in India
'Speak() is overriding Speak() in its base class (Human)
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")
'Important: As you expect, any call to Speak() inside this class
'will invoke the Speak() in this class. If you need to
'call Speak() in base class, you can use MyBase keyword.
'Like this
'Mybase.Speak()
End Sub
End Class
Carefully examine the code in Main()
Class MainClass 'Our main function Shared Sub Main() 'Let us define Tom as a human (base class) Dim Tom as Human 'Now, I am assiging an Indian (derived class) Tom=new Indian 'The above assignment is legal, because 'Indian IS_A human. 'Now, let me call Speak as Tom.Speak() 'Which Speak() will work? The Speak() in Indian, or the 'Speak() in human? 'The question arises because, Tom is declared as a Human, 'but an object of type Indian is assigned to Tom. 'The Answer is, the Speak() in Indian will work. This is because, 'most object oriented languages like Vb.net can automatically 'detect the type of the object assigned to a base class variable. 'This is called Polymorphism End Sub End Class
Lesson 8: Constructors & Destructors
Import the System namespace (already available in .NET)Imports SystemA Constructor is a special function, which is calledautomatically when a class is created. In VB.NET, you should useNew() to create constructors as in the below examples.Constructors can be overloaded (see Lesson 4), but unlikein functions, the Overloads keyword is not required.A Destructor is a special function, which is calledautomatically when a class is Destroyed. In VB.NET, you should useFinalize() routine to create Destructors.They are similiar to Class_Initialize and Class_Terminatein VB 6.0
Dog is a class
Class Dog 'The age variable Private Age as integerThe Default Constructor.
Public Sub New()
Console.Writeline ("Dog is Created With Age Zero")
Age=0
End Sub
The Parameterized Constructor
Public Sub New(val as Integer)
Console.Writeline ("Dog is Created With Age " + Convert.ToString(val))
Age=val
End Sub
This is the destructor.
Overrides Protected Sub Finalize()
Console.Writeline ("Dog is Destroyed")
End Sub
'The Main Function
Shared Sub Main()
Dim Jimmy, Jacky as Dog
'Create the objects
'This will call the default constructor
Jimmy=new Dog
'This will call the parameterized constructor
Jacky=new Dog(10)
End Sub
'The Destruction will be done automatically, when
'the program ends. This is done by the Garbage
'Collector.
End Class
Lesson 9: Property Routines
You can use both properties and fields to store information in an object. Whereas fields are simply public variables, properties use property proceduresto control how values are set or returned.You can use the Get/Set keywords for getting/setting properties.See the following example.Import the System namespace (already available in .NET)
Imports SystemDog is a class
Public Class Dog 'A private variable to hold the value Private mAgeOfDog as IntegerThis is our property routine
Public Property Age() As Integer
'Called when someone tries to retreive the value
Get
Console.Writeline ("Getting Property")
Return mAgeOfdog
End Get
Set(ByVal Value As Integer)
'Called when someone tries to assign a value
Console.Writeline ("Setting Property")
mAgeOfDog=Value
End Set
End Property
End Class
Another Class
Class MainClass 'Our main function. Execution starts here. Shared Sub Main() 'Let us create an object. Dim Jimmy as Dog Jimmy=new Dog 'We can't access mAgeofDog directly, so we should 'use Age() property routine. 'Set it. The Age Set routine will work Jimmy.Age=30 'Get it back. The Age GEt routine will work Dim curAge=Jimmy.Age() End Sub End Class
Lesson 10: A Simple Program
Let us analyze a simple program. First, let us import required namespacesImports System Imports System.ComponentModel Imports System.Windows.Forms Imports System.Drawing
'We are inheriting a class named SimpleForm, from the 'class System.Windows.Forms.Form ' 'i.e, Windows is a namespace in system, Forms is a 'namespace in Windows, and Form is a class in Forms. Public Class SimpleForm Inherits System.Windows.Forms.Form 'Our constructor Public Sub New() 'This will invoke the constructor of the base 'class MyBase.New()Set the text property of this class. We inheritedthis property from the base class.
Me.Text = "Hello, How Are You?" End Sub End Class
Public Class MainClass Shared Sub Main() 'Create an object from our SimpleForm class Dim sf as SimpleForm sf=new SimpleForm 'Pass this object to the Run() function to start System.Windows.Forms.Application.Run(sf) End Sub End Class
History
Nov 13,2004 - Prepared this article for publishing
