Download presentation
Presentation is loading. Please wait.
1
Constructors
2
You got plenty of experience using constructors in the Marching Band program. A constructor is the subroutine which creates objects from a class. Every class has a default constructor which takes no parameters– New(). This default constructor is there even if you don’t see it. 2
3
ThreeDPoint In the class definition, there is no Sub New. However, I can still call the default constructor like this: 3
4
Creating a Constructor However, we can create our own constructor. There are two main reasons for creating your own constructor: 1.To initialize the value of variables using parameters; and 2.To create any objects that the current object will need; that is, calling constructors of other classes. Here’s the Rank class’s constructor from Marching Band: Notice that it Initializes the mStepSize variable; Creates the 10 members of the rank by calling BandMember’s constructor. 4
5
Creating a Constructor Here’s a simple constructor for the ThreeDPoint class. It simply initializes the variables. 5
6
Constructors in Action To understand how to declare variables and create objects using constructors, View the ConstructorsInAction video. 6
7
Overloads VB allows functions and subs (including constructors) to be overloaded. This means that you can have two or more procedures with the same name. They just have to differ in the number and/or type of parameters. Overloads are used widely in the built-in VB.NET classes (you’ll see many in the graphics routines), but you can create your own overloads as well. 7
8
Overload Example 8
9
ToString Older versions of VB, including Visual Basic for Applications in Excel, do not have a “ToString” function. VBA is a loosely-typed language that does all sorts of datatype conversions in the background for you (sometimes well, sometimes not). VB.NET, the descendant of VBA (VB 6), is a strongly typed language, which means that functions, subs and properties can require a particular parameter type. If a String parameter type is required you can put ToString on the end of a variable or expression to convert it to a string. 9
10
ToString For example: Notice that when I try to put a numeric value into a Text property, I get an error: ToString is the cure: (Note: I added the extra blank lines so the error message wouldn’t cover up the line above. This doesn’t mean that I now approve of lots of blank lines!) 10
11
ToString The standard datatypes (even String) have built-in ToString methods. ToString can even be applies to expressions: However, the classes that you create will have a default ToString method that’s pretty useless: It just displays the name of the class. And this can be annoying when you start adding objects of your own classes to ListBoxes and ComboBoxes! 11
12
Using ToString to Format Numbers ToString can be used to format numbers, like this: 12
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.