So fields are the pieces of information that allow us to describe things in a class better. And fields are always of some particular type.
Adding Fields to the Class
Previously, all we told the computer about "Animals" in general was that they were called "Animal". We promised to later put more information about "Animals" between Class Animal … End Class.
Class Animal
...
End Class
Well, now we’re ready to do that. Let’s add some fields to our class definition:
Class Animal
Dim kindOfAnimal As String
Dim name As String
Dim numberOfLegs As Integer
Dim height As Integer
Dim length As Integer
Dim color As String
Dim hasTail As Boolean
Dim isMammal As Boolean
Dim spellingCorrect As Boolean
End Class
(to keep your code neat and readable, it's usual to indent the fields as shown above. To do this, press the TAB key on the keyboard. You can also select a few rows and indent them all with one press of the TAB key.)
Using Fields with Specific Objects
Okay, so we've explained to the computer that ALL Animals have these fields. Now, let’s ask it to create an instance representing a specific one of these animals (as we did in the previous chapter) and then let's tell the computer some things about that specific animal - by giving values for each field.
Dim fiddlesticks As Animalfiddlesticks = New Animal()
fiddlesticks.kindOfAnimal = "Cat"
fiddlesticks.name = "Fiddlesticks The Cat"
fiddlesticks.numberOfLegs = 4fiddlesticks.height = 50fiddlesticks.length = 80fiddlesticks.color = "Black"
fiddlesticks.hasTail = True
fiddlesticks.isMammal = True
Notice that, for string fields, we always put the value inside quotes (""), but not for the other types.
It’s worth reminding you at this point, that the object name we chose, "fiddlesticks", is of no sentimental importance to the computer. It will work just as happily with this object if we replace all the "fiddlesticks" names with the name "X", or any other name of our choosing:
Dim X As AnimalX = New Animal()
X.kindOfAnimal = "Cat"
X.height = 50X.length = 80X.color = "Black"
X.hasTail = True
X.isMammal = True
Building Block : Fields |
A class normally has one or more fields, which allow us to describe the detail of things of that class.
Class SchoolKid
Dim firstName As String
Dim lastname As String
Dim age As Integer
Dim isWideAwake As Boolean
End Class
Although the fields can be written against the margin, it is good practice to indent them one tab space toward the right by pressing the TAB key on the keyboard. This makes the code easier to read. These fields are always of a particular type. There are many different possible types, but here are some common ones : TypeWhat it meansExamples of values StringMainly holds things like words and sentences, which are made up by "stringing" letters of the alphabet, and some other symbols, together "Sam""Eight-legged Octopus""Girls are too clever to fall out of their prams" IntegerIt is a kind of whole number.32828000-520 BooleanIt means "true or false"TrueFalse When you define a field in a program, you must enter a type and a name for the field :
The type must be entered exactly as the computer knows it. The field’s name is a word of your own choosing like "isWideAwake" and can be written with both small and capital letters. Things such as spaces are not allowed. When you work with a specific object, you normally assign values to the fields, which help to describe the object. If, for example, we have an object named schoolKid, we could give values to its fields as follows :
schoolKid.firstName = "Jiminy"
schoolKid.age = 13
We separate the object name and field name with a period ".". So schoolKid.firstName = "Jiminy" means "put the value 'Jiminy' into the schoolKid object's firstName field". |
Private, Protected and Public Fields
This topic won't be too important while you're first learning Visual Basic, but you may see words like "Private", "Protected" and "Public" at some later point and wonder what they mean. So let's talk about them.
Class Animal
Dim kindOfAnimal As String
Dim name As String
Dim numberOfLegs As Integer
Dim height As Integer
Dim length As Integer
Dim color As String
Dim hasTail As Boolean
Dim isMammal As Boolean
Dim spellingCorrect As Boolean
End Class
Class MyTestClass
End Class
It is possible to have things from one class, such as MyTestClass above, talk about things in another class like Animal.
When fields are declared as above, we can decide whether we want to allow other classes to access them or not. Sometimes it's quite important to make the fields "Private" because, for example, another class might put some nasty values into the fields and break the program. Setting a field somewhere in the range from Private through to Public is about how safe we need our class to be.
Notice the different protection levels of the kids in the family portrayed above. Sally, the baby, is being kept Private – she is not being allowed out of the house and enjoys the highest level of safety. Only those who are most trusted can interact with her. Billy has the freedom of the front and back yards too but is still somewhat Protected. Tom, the eldest, is Public and so anybody else out there can interact with him in whatever way they choose.
So we can add a word at the beginning of the field declarations, as follows:
Class Animal
Public kindOfAnimal As String
Public name As String
Public numberOfLegs As Integer
Public height As Integer
Public length As Integer
Public color As String
Dim hasTail As Boolean
Protected isMammal As Boolean
Private spellingCorrect As Boolean
End Class
You might wonder what happens if we leave these words out. The answer is that the computer silently treats it as if you'd written "Private" in front of it since "Private" is the default setting. So the hasTail field above will automatically become Private.
What do these words mean?
Private means "only things in this class can access this field"
Public means "any class can access this field"
Protected means "only closely-related classes can access this field"
The following two classes illustrate how Public and Private work in practice. We’re not going to discuss Protected further here, but you can read up in the Visual Basic Express help if you’re curious about it,
We first define, as before, some private and public fields in the "Animal" class and then try to access them from the "Zoo" class.
Class Animal
Public kindOfAnimal As String
Public name As String
Public numberOfLegs As Integer
Public height As Integer
Public length As Integer
Public color As String
Dim hasTail As Boolean
Protected isMammal As Boolean
Private spellingCorrect As Boolean
End Class
Class Zoo
Dim a As Animal = New Animal()
' The following line will succeed because the "Zoo" class is allowed ' to address public fields in the "Animal" class a.kindOfAnimal = "Kangaroo"
' The following lines will both FAIL because the "Zoo" class ' is not allowed to address private or protected fields a.isMammal = False ' Try to access a protected methoda.spellingCorrect = True ' Try to access a private method
End Class
Methods
Programs would be rather useless if they could only allow us to describe objects. Clearly we want them to "do things" too:
Now think back to when your teacher taught you to add numbers. Most likely he or she first taught you HOW to add numbers – probably showing you some steps you should follow. In other words you were first taught the METHOD of solving this kind of problem. A method is a set of step-by-step instructions explaining how to do something.
Then, once you have a method for solving problems of a particular type, you can be given all sorts of different problems of that type and you will be able to solve them – by following the steps in the method.
Similarly, if we want the computer to do things, we must write code to tell it how to do them – in other words, we must describe the method it should use to achieve these things. It can then use that method each time we give it a problem of that type.
In Visual Basic, a method is a piece of code that describes to the computer the way that it should do something. When we later call that method, the computer runs through the code, doing exactly what we wrote.
We can describe a simple method to the computer like this:
But a method is pointless if it does nothing – so let’s add some code inside the method that can do something.
Sub SayHello()
Console.WriteLine("Hello")
End Sub
(For the sake of neatness, you should indent code in a method one tab space to the right by pressing the TAB key)
If we were to call this method now, it would write the word "Hello" to the screen. Not a very difficult problem – so the method is quite simple.
What does Sub mean?
You may feel confused by this strange word "Sub" in the example above, and wonder why we write it there. So let’s look at this word briefly. When we use a Sub, it means that once the method is finished running, it will send back a "nothing" value – in other words, nothing! It doesn’t mean the method does nothing, but rather that once it’s finished doing its thing it sends nothing back. This suits us fine in our SayHello method above because, after it’s written the word "hello", it doesn’t need to send anything back. That’s all we needed it to do.
This will make more sense when we discuss some cases where we might want to send something back from a method, which we’ll do a little later on in the journey.
Calling a Method
By writing down the code above, we have taught the computer HOW to write hello to the screen, but we have not yet told it to actually do this.
It’s like your teacher showing you how to add numbers, and getting you to write the method down, but not actually asking you to do any particular sum.
To get the computer to "do it", we must call the method. This is sometimes done by simply writing the name of the method, along with the parenthesis, like this:
When the computer hits this line, it does not know by itself how to handle such a command – so it goes looking frantically for a method that you’ve written called "SayHello". If it finds one, it quickly runs through each line in that method, doing whatever you wrote there.
Then it comes back, dripping with pride, "Look what I did", and takes all the credit.
Building Block : Declaring and Calling a Method |
A class most often has one or more methods. These do something – they perform some action. They’re called methods because it is here that we describe to the computer the method of doing something: the step-by-step instructions explaining how to do something.
Class Person
' Fields
Public firstName As String
Public lastName As String
' A method
Public Sub ShowFullName ()
Console. WriteLine("Name is " & Me.firstName & " " & Me.lastName)
End Sub
…
End Class
An ampersand sign "&" is a way to add strings onto the end of each other, and recall that we also need quotes "" around text characters but not variables. The single quote "'" is a way to tell the computer to ignore everything on this line. We use it to insert human-readable comments and notes into our code. The word "Me" refers to "this object I’m talking about". So "Me.firstName" refers to the firstName field of the current object (which is Jiminy in the example below). A method is set into action by writing the method name, including the parenthesis, somewhere in your program.
Dim Jiminy As Person
Jiminy = New Person()
Jiminy.firstName = "Jiminy"
Jiminy.lastName = "Cricket"
Jiminy.ShowFullName()
When the ShowFullName line is encountered, the computer goes back and finds the method of the specified name and runs through the code written in it, step by step. |
More About Methods
In the previous chapter we introduced methods, but there is a lot more to them than what we covered in the last chapter. This chapter covers some of the more advanced aspects of methods. At first, you'll be able to get by with just the basics, but at some stage you'll need to understand things like sending values into a method and getting values out of a method.
Parameters
Let’s imagine you get the urge to have the computer write the following to the screen:
Hello Jo
Hello Sam
Hello You
Here’s one way to do it … we could write a separate method for every situation:
Sub WriteHelloJo()
Console.WriteLine("Hello Jo")
End Sub
Sub WriteHelloSam()
Console.WriteLine("Hello Sam")
End Sub
Sub WriteHelloYou()
Console.WriteLine("Hello You")
End Sub
and then call the methods like this :
WriteHelloJo()
WriteHelloSam()
WriteHelloYou()
But that seems like rather a waste of energy since the three methods are all almost the same. What if we could use one WriteHello method and, each time we call it, just tell it the part that needs to be different.
This can be done by writing the method as follows:
Sub WriteHello(ByVal someName As String)
Console.WriteLine("Hello " & someName)
End Sub
and then calling it like this :
WriteHello("Jo")
WriteHello("Sam")
WriteHello("You")
As you can see this saves both space and effort. You should always try to write as little code as possible. Generally speaking, the shorter the program is, the smarter is the programmer.
When we write the method in this smart new way,
Sub WriteHello(ByVal someName As String)
Console.WriteLine("Hello " & someName)
End Sub
we’re really saying "Whenever I call this method, I’ll pass it a string of letters holding some name. Whatever that thing is that I pass you, I want you to write after the word "Hello".
The thing in the parenthesis (ByVal someName As String) is called a parameter. It allows you to pass a value into the method when you call it.
After all, when your teacher taught you how to add numbers, she didn't teach you every single possibility - she taught you the method and then threw a whole bunch of different problems at you: "Add 2 and 5. Now add 7 and 3." It's as if she gave you a method called AddNumbers and passed you different parameters each time. No matter what parameters she sent you, you were able to work out the answer because you knew the method.
The computer could care less what name you give to a parameter – but is very fussy about your using the same name throughout your method. This, for example will work correctly:
Sub WriteHello(ByVal x As String)
Console.WriteLine("Hello " & x)
End Sub
But this will not :
Sub WriteHello(ByVal someName As String)
Console.WriteLine("Hello " & someBodysName)
End Sub
Can you see the mistake? "someName" and "someBodysName" are different - this will confuse our binary friend and cause it to throw a tantrum.
It is also perfectly legal to have more than one parameter in a method; you just need to separate them with commas:
Sub WriteHello(ByVal firstName As String, ByVal lastName As String)
Console.WriteLine("Hello " & firstName & " " & lastName)
End Sub
But then you must pass in the right number of values when you call the method
WriteHello("Jiminy", "Cricket")
This will, of course, write out to the screen "Hello Jiminy Cricket".
Sending Wrong Parameter Types
Suppose that, back when you first learned how to add numbers, your teacher suddenly threw this problem at you: "Add the numbers 5 and flower".
How would you have responded? Probably something like this: "Flower is not a number! You can't add those." Quite right.
In the same way, the computer will complain bitterly if you send it a value of the wrong type. This is a common programming error. So if things aren't working as you'd expected, go back and check that you're sending values whose types match those defined in the method.
Building Block : Parameters |
If we want to pass specific values into a method, we define parameters in the method :
Class Person' Fields
Dim firstName As String
Dim lastName As String
' Method
Public Sub LuckyNumber(ByVal numberOfTeeth As Integer, ByVal age As Integer)
Console.WriteLine("Lucky number is " & numberOfTeeth * age)
End Sub
…
End Class
And then, whenever we call the method, we make sure we pass the right kind of values into those parameters. In the example below we pass in two integer numbers because the parameters for the method "LuckyNumber" were defined as integers.
Dim jiminy As Person
jiminy = New Person()
jiminy.LuckyNumber(24, 14)
|
Methods that Send Values Back
The methods we’ve shown thus far have written something to the screen and then simply given control back to the line that called them – "I’ve done my bit. Back to you Jack". Sometimes, however, we want the method to send some useful value back to the line of code that called it.
Here’s an example. We’ll write a method that looks up how many legs a specified animal has and then sends that number back to whatever called the method.
Here’s how we could write the method – remember that this is the part where we teach the computer HOW to do something - we're writing the method down. I’ll first write what I want the computer to do in English, and then I’ll write it in Visual Basic:
If the animal that we’re talking about is named "elephant", then the Number of Legs = 4.
Otherwise, if the animal that we’re talking about is named "turkey", then the Number of Legs = 2.
Otherwise, if the animal that we’re talking about is named "oyster", then the Number of Legs = 1.
Otherwise, for animals named anything else, then the Number of Legs = 0.
Function NumberOfLegs(ByVal animalName As String) As Integer
If animalName = "elephant" Then ' If the name of the animal equals "elephant"
' Send back the value 4
Return 4
Else If animalName = "turkey" Then ' Otherwise, if it equals "turkey"
' Send back the value 2
Return 2
Else If animalName = "oyster" Then ' Otherwise, if it equals "oyster"
' Send back the value 1
Return 1
Else ' Otherwise (under all other conditions)
' Send back the value 0
Return 0
End If
End Function
And then we could call the method. Let’s call it twice:
1. Dim i As Integer ' Create a variable "i" of integer type
' to hold the Number Of Legs value
2. i = NumberOfLegs("turkey") ' Now i = 2 from the NumberOfLegs method above
3. Console.WriteLine("The turkey has " & i & " legs")
4. i = NumberOfLegs("monkey") ' Now i = 0 from the NumberOfLegs method above
5. Console.WriteLine("The ape has " & i & " legs")
Line 3 will write out "The turkey has 2 legs" and line 5 will write "The ape has 0 legs". So the method passes back a value, and that returned value can be plugged directly into the line of code that called the method.
Why did we define the method like this?
Function NumberOfLegs(ByVal animalName As String) As Integer
...
End Function
instead of like this :
Sub NumberOfLegs(ByVal animalName As String)
...
End Sub
or like this :
Private Function NumberOfLegs(ByVal animalName As String) As String
...
End Function
It is, of course, because we wanted the method to send back a whole number in this case; not a "nothing" value, not a string of letters but a whole number. And one data type for working with whole numbers is the "Integer".
When we write a method, we always specify what kind of data that method will return. If we don’t need it to return anything, we use a Sub to specify that it will return "nothing".
Sub JustWriteSomething(ByVal someThing As String)
Console.WriteLine(someThing)
End Sub
Lastly, you will probably have figured out that the word "Return" is the part that actually sends back a value. As soon as the computer encounters the "Return" word it jumps out of the method and sends back whatever it was asked to send back.
Building Block : Return Values |
Sometimes we want to pass a value back from a method. In such a case, instead of making the method a "Sub", which means "we’ll be sending nothing back", we use a function and specify the particular data type that the method will return.
Class Person
' Fields
Dim firstName As String
Dim lastName As String
' Method
Function LuckyNumber(ByVal numberOfTeeth As Integer, ByVal age As Integer) _
As Integer
Return (numberOfTeeth * age)
End Function
End Class
The value returned is then automatically available wherever we called the method. We could, for example, use the returned value in either one of the following ways: We could first store the answer in a variable and then make use of the variable value in a separate statement.
Dim Susy As Person
Susy = New Person()
Dim num As Integer = Susy.LuckyNumber(24,14)
Console.WriteLine("Susy's lucky number is " & num)
Or we could call the method directly in our WriteLine statement like this :
Console.WriteLine("Susy’s lucky number is " & Susy.LuckyNumber(24, 14))
|
Public, Private and Protected Methods
Just as with fields (see the previous chapter), methods can be called from other classes. We may want to either allow this or prevent it.
By default, all methods will be treated as "Private", meaning that they can only be used inside their own class. If you wish to open this up so that other classes can call them, you can add a word such as "Public" at the beginning of the declaration.
Public Sub JustWriteSomething(ByVal someThing As String)
Console.WriteLine(someThing)
End Sub
Some areas in the real world are "out of bounds" unless you’re specially authorized. Like in restaurants, only the chefs, waiters and waitresses can go into the kitchen which is a "Private" area. Whereas, the dining room is a "Public" area – everyone can walk around in there. In a similar way, some code is out of bounds to other classes.
In an earlier section, we used an example with Private and Public fields. Let’s add to that example and include some Private and Public methods in the "Animal" class and then try to access them from the "Zoo" class.
Class Animal
Public kindOfAnimal As String
Public name As String
Public numberOfLegs As Integer
Public height As Integer
Public length As Integer
Public color As String
Dim hasTail As Boolean
Protected isMammal As Boolean
Private spellingCorrect As Boolean
' Public method that retrieves information about what food the animal eats
Public Function GetFoodInfo() As String
' Imagine we had some code here that searched a database
...
End Function
' Private method to check whether the animal’s type was spelled correctly
Private Sub CheckSpelling()
' Imagine we had some spell checking code here
...
End Sub
' Protected method that decides whether the animal type is a valid one
Protected Function IsValidAnimalType() As Boolean
' Imagine we had some code here to test valid animal types
...
End Sub
...
End Class
Class Zoo
Dim a As Animal = New Animal()
a.name = "Kangaroo"
Dim food As String
Dim animalExists As Boolean
' The following will succeed because the "Zoo" class is allowed' to address public methods in the "Animal" classfood = a.GetFoodInfo() ' Call a public method' The following lines will both FAIL because the "Zoo" class' is not allowed to address private or protected methodsa.CheckSpelling() ' Try to call a private method
animalExists = a.IsValidAnimalType() ' Try to call a protected method
End Class
Constructor Methods
You will very often see classes written to include a rather special kind of method called a "constructor". The name of a constructor method is always New and there is no return type included.
It's called a constructor method because it helps to "construct" or build the object when it is first created. It is good practice to write a constructor method in your classes.
Class Person' Fields
Dim firstName As String
Dim lastName As String
' Constructor Method for the Person Class
Public Sub New()
firstName = "Johnny"
lastName = "Rocket"
End Sub
End Class
A constructor method is treated specially - it gets automatically run whenever an instance of the class is created.
Reminder:
By "an instance of the class", we mean a specific object of the class. For example, in the earlier section on "objects" we highlighted "Jeremy the Gorilla" as a specific object, or instance, of the class named Animal.
So if we executed the following code...
Dim p As Person = New Person()
Console.WriteLine(p.lastName)
we would find it would write out the word "Rocket". By creating a "Person" object we automatically and invisibly ran the "Person" constructor method, which sets the lastName to "Rocket" in this case.
Here’s a similar example from the real world. When a "new instance of a kid" is born at a hospital, somebody automatically marches into the room and takes care of a few details to make sure this new instance is properly registered and legally ready to participate in the world – before it leaves the hospital.
This action is similar to a constructor method being run on a class – before the new class instance is allowed to do anything, the constructor method is run. In that constructor method, you include anything you feel needs to be done automatically before the object is to be considered "ready for the world".
Constructors with Parameters
You may write a constructor method to include parameters. Here's an example of a class with two different constructor methods:
Class Person' Fields
Dim firstName As String
Dim lastName As String
' First constructor method
Public Sub New()
firstName = "Johnny"
lastName = "Rocket"
End Sub
' Second constructor method
Public Sub New(ByVal f As String, ByVal l As String)
Me.firstName = f
Me.lastName = l
End Sub
End Class
And now there are now two different ways we could construct the object:
Either like this:
Dim p As Person = New Person()
And the p.lastName field will automatically get the value "Rocket".
Or like this:
Dim p As Person = New Person("Jiminy","Cricket")
And the p.lastName field will get the value "Cricket".
Recall that the word "Me" refers to "this object we're creating". So it is effectively saying "set this new object's firstname and lastname fields to whatever values get passed to the constructor method".
Events
In the real world, events occur all the time. There are some that we cannot control, such as the sunrise and sunset (I'd like to see you try and make the sun rise and set by yourself), and there are other events that we can choose to kick off, such as music coming out of a stereo's speakers.
Events in the computer's world are more like these:
Obviously, if a button is clicked, we want the computer to do something - otherwise why bother having the button there in the first place. But the computer expects you to tell it that this click is important to you - and it also expects you to specify what you want it to do if the button does get clicked.
Let's take the button clicking example, since it's probably the most common event, and follow through how to deal with it. Let's assume you have, in your program, a button object named mrButton, with the words "Click me" written on it.
In fact, how about trying this yourself as you follow the discussion? To get started:
Open Visual VB.Net Express by clicking START -> All Programs -> Microsoft Visual VB.Net 2005 Express Edition
Start a new Windows application project: Select File -> New Project and then choose the project type "Windows application".
Visual VB.Net Express will put down a few files with some "skeleton code".
In the "Solution Explorer" window on the right side (where all the files are listed), delete the file named Form1.vb.
Now right click the project name in the "Solution Explorer" and select Add -> Add New Item.
Double-click the file named Program.vb and delete all the skeleton code that was automatically inserted.
To create a program with an instance of a button, type the following code into Program.vb exactly as it is here (except that you may ignore the fact that some words are written in italics or bold)
Imports System
Imports System.Windows.Forms
Class MyButtonClass
Inherits Form
Private mrButton As Button
' Constructor method
Public Sub New()
mrButton = New Button()
mrButton.Text = "Click me"
Me.Controls.Add(mrButton)
End Sub
' Main method
Shared Sub Main()
Application.Run(New MyButtonClass())
End Sub
End Class
|
Run the program by pressing the F5 key on the keyboard (or by clicking the green Run button). If you encounter any error messages, check carefully for typing errors. If the program runs correctly, you should see a form displayed with a button named "Click me". At this stage, the button will not do anything if you click it. Quite a let-down, I know, but we’re getting there.