Beruflich Dokumente
Kultur Dokumente
8
21
27
Review
35
37
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2002 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Active Directory, ActiveX, bCentral, BizTalk, FrontPage,
IntelliSense, JScript, Microsoft Press, MSDN, MSN, Outlook, PowerPoint, Visual Basic,
Visual C++, Visual C#, Visual Studio, Win32, and Windows Media are either registered
trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
iii
Instructor Notes
Presentation and
practices:
135 minutes
Lab:
30 minutes
Required materials
Preparation tasks
This module provides students with an explanation of how to create and use
classes. The module explains the concepts of abstraction, encapsulation,
instantiation, initialization, and constructors and destructors. This module also
describes inheritance, polymorphism, and namespaces.
After completing this module, students will be able to:
!
Create a new class, including its methods, properties, and data members
with appropriate access levels.
Create and use an instance of a class, including instance and shared data
members, and shared and non-shared methods.
iv
This topic describes the role of abstraction and encapsulation in creating a class.
It is important to emphasize that this is just a basic introduction to a complex
topic. You can mention use-case analyses and diagrams, but these tools are not
mentioned in the topic. When describing the concept of encapsulation, use the
automated teller machine example to help students distinguish between what
the user sees and what is encapsulated or hidden.
What Is an Object?
This topic is best taught by demonstrating the Object Brower in the Microsoft
Visual Studio .NET development environment as you explain what the Object
Browser is and how to use it.
This topic demonstrates how to create a new class in Microsoft Visual Basic
.NET. The module demonstrates creating a class from the Project menu. You
can show the students alternative methods if you choose.
In this topic, students learn how to add an instance data member to a class. This
topic also shows students how to refer to the data member by using the Me
keyword. In addition, this topic shows students how to assign access modifiers.
Relate this topic to the boundary that encapsulation provides. Explain that those
members of the entity that are accessible only from the inside are private and
that those members of the entity that are accessible from both the inside and the
outside are public.
In this topic, students learn how to add methods to a class. This topic also
explains method overloading. Explain that method overloading occurs when a
class contains two or more methods with the same name but different
signatures.
In this topic, students learn how to add properties to a class. Explain that
students can assign the properties and retrieve the values of the properties from
the class. This topic also describes how to use the ReadOnly and WriteOnly
specifiers.
How to Create an
Instance of a Class
This topic demonstrates how to create an instance of a class. Explain that this
means creating an object to execute the properties and methods of a class. Point
out the instance data member in the sample code on the slide.
Practice: Creating a
Class
This practice provides the steps to create a new class. This practice is designed
to take approximately 15 minutes.
How to Use
Constructors
This topic demonstrates the use of constructors. Explain the use of the New
keyword to initialize new objects.
This topic demonstrates the use of destructors. Explain the use of the Finalize
destructor subroutine to clean up resources such as database connections.
This topic explains that shared data members allow multiple class instances to
refer to a single class-level variable instance.
This topic explains how to use shared methods to design functions that can be
called without creating an instance of the class. Explain that shared members
can only access data that is marked with the Shared keyword.
Practice: Creating
Shared Methods
In this practice, students will create and use a class that has a shared method to
convert degrees Fahrenheit to degrees Celsius. This practice is designed to take
approximately 15 minutes.
vi
This topic describes how inheritance works. Explain that, in Visual Basic .NET,
students can use inheritance to derive a class from an existing base class. The
derived class can inherit all the base class properties, methods, data members,
events, and event handlers, making it easy to reuse the base class code
throughout an application.
What Is Polymorphism?
Comparing Classes to
Structures
This topic helps students distinguish between classes and structures. Explain
that classes and structures are similar in several ways: both can define data
members, properties, and methods. However, classes provide some advanced
features that students can use.
How to Organize
Classes into
Namespaces
Review
The review questions are mostly based on conceptual understanding and on
procedures that were covered thoroughly in the module. You can use a
discussion format to answer the questions so that everyone gets the benefit of
knowing the right answers.
1. It is important for students to recognize the process of abstraction.
2. It is important for students to recognize the process of encapsulation.
3. This question provides a chance to write the code that adds a new project
and adds an instance data member and method to the code.
4. This question provides a chance to write the code to create a new class and
add a private data member.
5. This question provides a review of how to initialize and un-initialize
objects.
6. Use this question to reinforce the concept of inheritance.
vii
Overview
Create
Interface
Write
Debug
Code
and Deploy
Use Visual
Studio .NET
Access
Data
Debug
and Deploy
Understanding Classes
Inheritance,
Polymorphism, and
Namespaces
This module explains how to create and use classes. The module provides a
conceptual understanding of abstraction, encapsulation, instantiation,
initialization, constructors, and destructors. This module also describes
inheritance, polymorphism, and namespaces.
Objects are fundamental to Microsoft Visual Basic .NET programming.
Forms, controls, and databases are all objects. In this module, you will learn
how to create your own objects from classes you define and how you can use
objects to simplify your coding and increase code reuse.
Objectives
Create a new class, including its methods, properties, and data members.
Create and use an instance of a class, including instance and shared data
members, and shared and non-shared methods.
Animation script
In Visual Basic .NET, you can use object-oriented programming elements such
as classes and objects.
A class can be a concrete entity, like a clock, or an abstract entity, like time.
Think of a class as a template or blueprint that has variables, methods,
properties, and events.
An object is an instance of the class. For example, this blueprint for a house is
like a classthe House classand each of the actual houses built from the
blueprint is like an instance of the House class.
In Visual Basic .NET, you can extend your class by inheriting from it. The class
you inherit from is called a base class. The class you extend is called a derived
class. Derived classes inherit and can extend the properties, methods, and
events defined in the base class.
Lesson agenda
Lesson objectives
What Is a Class?
What Is an Object?
Use the Object Browser to examine classes, objects, and other programming
elements.
What Is a Class?
!
What is encapsulated:
//verify language
//authenticate PIN
//validate account bal
//adjust account bal
Definition
Using abstraction
Example of abstraction
The Visual Basic .NET form you have been working with is a good example of
abstraction. The essential properties of a form, such as caption and background
color, have been abstracted in the Form class. Some essential operations that
have been abstracted are open, close, and minimize.
Using encapsulation
Example of
encapsulation
What Is an Object?
!
"
"
12
Object
Object
123
245
245
In general, to execute the methods and use the properties of a class, you need to
create an instance of the class. An instance of a class is called an object. The
words class and object are used so much in object-oriented programming that it
is easy to get the terms mixed up. Think of a class as an abstract representation
of something and an object as a usable example of the thing the class
represents.
Definition
Example of an object
The word car has different meanings in different contexts. Sometimes the word
refers to the general concept of a car or the set of all cars. Using the word in this
way is analogous to using the word class. Sometimes the word car refers to a
specific car. Using the word in this way is analogous to using the word object.
Identity
Objects have identity. Identity is the characteristic that distinguishes one object
from all other objects.
Behavior
State
Objects have state. State is the characteristic that refers to the inner workings of
an object that enable it to provide its defining behavior. A well-designed object
keeps its state inaccessible. State is closely related to abstraction and
encapsulation. You do not care how an object performs its actions, but you do
care that it performs those actions. Two objects might coincidentally contain
the same state, but they are still two different objects.
Members
Members
Pane
Pane
Objects
Objects
Pane
Pane
Description
Description
Pane
Pane
To open the Object Browser, either press CTRL+ALT+J or, on the View menu,
point to Other Windows and then click Object Browser.
The Object Browser is composed of three panes:
!
The Objects pane displays all container objects in the browsing scope in a
tree view. When you expand an element by double-clicking it or by clicking
the plus sign (+) next to its name, the elements defined within it appear.
The Members pane displays the members of an element when you select the
element in the Objects pane.
Description
Icon
Description
Namespace
Module
Class
Structure
The Microsoft .NET platform provides the Microsoft .NET Framework class
library, but you can also create your own classes. This lesson describes how to
create a new class, add data members, methods, and properties to the class, and
set public and private access modifiers. This lesson also describes how to create
an instance of a class and how to initialize and un-initialize objects.
Lesson agenda
Lesson objectives
Create an object.
BankAccount
Public
BankAccount
Public Class
Class Class1
Class1
End
End Class
Class
After you use the process of abstraction to determine the relevant entities for a
business problem, you are ready to create classes that reflect the entities in the
abstraction.
10
Public
Public Class
Class BankAccount
BankAccount
Private
Private balance
balance As
As Double
Double
End
End Class
Class
Keyword
Keyword
Definition
Definition
Public
Public
Accessible
Accessibleeverywhere
everywhere
Private
Private
Accessible
Accessibleonly
onlywithin
withinthe
thetype
typeitself
itself
Accessible
Accessibleonly
onlyby
byclasses
classeswhich
whichinherit
inheritfrom
fromthe
the
class
class
Protected
Protected
After you add a new class to your project, you can add data members to your
class. A data member specific to an instance of the class is called an instance
data member. When you add instance data members to a class, you specify the
level of access by setting the access modifiers.
Example
Me keyword
You can also refer to the data member balance by using the Me keyword, as
shown in the following example:
Me.balance
You can control the accessibility of entities inside this class: some will be
accessible only from the inside and others will be accessible from the inside and
the outside. Those members of the entity that are accessible from only the
inside are private. Those members of the entity that are accessible from both the
inside and the outside are public. For example, you would need to make the
instance data member balance private so the balance of the account could not
be changed except from inside the BankAccount class.
You can also use the Protected keyword to limit accessibility to classes that
inherit from this class. You will learn more about inheritance in the last lesson
in this module.
11
Public
Public Class
Class BankAccount
BankAccount
Private
Private balance
balance As
As Double
Double
Public
Public Sub
Sub Deposit(ByVal
Deposit(ByVal amount
amount As
As Double)
Double)
balance
+=
amount
balance += amount
End
End Sub
Sub
End
End Class
Class
!
You can add methods to a class. When you add methods, you specify the level
of access by setting the access modifier. Methods include functions and Sub
procedures.
Example
In this example, the Deposit method is public so that the users of this class can
deposit money into an account by using the Deposit method.
Overloading methods
Method overloading occurs when a class contains two or more methods with
the same name but different signatures. An example of an overloaded method is
the MessageBox.Show method. The Show method provides twelve overloads.
These overloads make the method more flexible for users of the method.
To overload a method, use the Overloads keyword. The Overloads keyword
declares a property or method with the same name as an existing member, but
with a parameter list that is different from the original member.
The following example shows an overloaded method named Execute. The first
Execute method does not take any parameters. The second one takes a string as
a parameter.
Public Overloads Sub Execute( )
...
End Sub
Public Overloads Sub Execute(ByVal connection As String)
...
End Sub
12
Adding a property:
Public
Public Class
Class BankAccount
BankAccount
Private
Private customerName
customerName As
As String
String
Public
Public Property
Property Name(
Name( )) As
As String
String
Get
Get
Return
Return customerName
customerName
End
Get
End Get
Set(ByVal
Set(ByVal Value
Value As
As String)
String)
customerName
customerName == Value
Value
End
End Set
Set
End
End Property
Property
End
End Class
Class
You can add properties to a new class in your project. You can assign the
property, and you can retrieve the value of the property from the class.
Adding properties
To add property members to a class, you usually define a private data member
and public property procedures. You can perform two types of procedures on
properties in Visual Basic .NET: Get and Set.
Example
The Get procedure retrieves the property value from the class. It should not
change the value.
Use the ReadOnly specifier in the property declaration to create only the Get
property. Use the WriteOnly specifier in the property declaration to create only
the Set property.
13
Module
Module Bank
Bank
Sub
Sub Main
Main
Dim
Dim account
account As
As New
New BankAccount(
BankAccount( ))
account.Deposit(500.00)
account.Deposit(500.00)
End
End Sub
Sub
End
End Module
Module
To execute the methods and use the properties of a class, you must create an
instance of the class. An instance of the class is called an object.
Syntax
To create an instance of a class, you declare a variable of the type of the class
and use the New keyword, as shown in the following line of code:
Dim objectname As New objecttype( )
Example
14
15
4. In the method, increment the value of the balance by adding amount to it, as
follows:
customerBalance += amount
8. Create a read-only property called Balance that returns the current balance,
as follows:
Public ReadOnly Property Balance( ) As Double
Get
Return customerBalance
End Get
End Property
16
The completed code for the BankAccount class should look like the following:
Public Class BankAccount
Private customerBalance As Double
Private customerName As String
Public Sub Deposit(ByVal amount As Double)
customerBalance += amount
End Sub
Public ReadOnly Property Balance( ) As Double
Get
Return customerBalance
End Get
End Property
Public Property Name( ) As String
Get
Return customerName
End Get
Set(ByVal Value As String)
customerName = Value
End Set
End Property
End Class
4. Use the Name property to assign the name to the account, as follows:
account.Name = "Joe"
5. Use the Deposit method to deposit money into the account, as follows:
account.Deposit(500)
6. Use a message box to display the account name and balance, as follows:
MessageBox.Show ("Name: " & account.Name & _
". Balance: $" & account.Balance( ))
7. Change the startup object for the project to use Sub Main.
8. Build and run the program.
17
The completed code for the TestHarness module should look like the following
code:
Module TestHarness
Public Sub Main( )
Dim account As New BankAccount( )
account.Name = "Joe"
account.Deposit(500)
MessageBox.Show("Name: " & account.Name & _
". Balance: $" & account.Balance( ))
End Sub
End Module
Solution files
The solution files for this practice are located in the install_folder\Practices\
Mod07\CreatingClass\Solution folder.
18
Public
Public Sub
Sub New(
New( ))
'' Perform
Perform simple
simple initialization
initialization
value
=
1
value = 1
End
End Sub
Sub
!
Public
Public Sub
Sub New(ByVal
New(ByVal ii As
As Integer)
Integer)
'' Overloaded
without
Overloaded without Overloads
Overloads keyword
keyword
'' Perform
Perform more
more complex
complex initialization
initialization
value
value == ii
End
End Sub
Sub
In Visual Basic .NET, you control the initialization of new objects by using
constructors. To create a constructor for a class, create a procedure named Sub
New anywhere in the class definition.
The code in the Sub New block will always run before any other code in a
class.
The Sub New constructor will only run once, when an object is created.
The following example shows how to use the Sub New constructor:
Public Sub New( )
' Perform simple initialization
intValue = 1
End Sub
The following line of code creates an object from a class named BankAccount,
which is already defined in the application.
Dim myAccount As New BankAccount( )
You can overload New and create as many class constructors as you require.
This is useful if you want to initialize your object when you create it.
Overloading
constructors
You can overload constructors just as you can overload any other method in a
class. However, you cannot use the Overloads keyword when overloading
constructors. The following example shows how to overload New and create
multiple class constructors:
Class BankAccount
Private balance as Double
Sub New( )
' Initialize balance
balance = 0.0
End Sub
Sub New(ByVal amount As Double)
balance = amount
End Sub
End Class
One of the constructors in the above example takes a parameter. If you are
creating an object from such a class, you can include its parameters in the
declaration. The following example shows how to call the New method that
takes a parameter.
Dim myAccount As New BankAccount(120.00)
19
20
Protected
Protected Overrides
Overrides Sub
Sub Finalize(
Finalize( ))
'' Can
Can close
close connections
connections or
or other
other resources
resources
conn.Close
conn.Close
End
End Sub
Sub
In Visual Basic .NET, you can control what happens during the destruction of
objects by using procedures called destructors.
The system calls the Finalize destructor before releasing the object. You can
use it to clean up open resources, such as database connections, or to release
other resources. However, there is a delay between when an object loses scope
and when the Finalize destructor is called.
Running Sub Finalize causes a slight loss in performance, so you should define
a Sub Finalize method only when you need to release objects explicitly.
Note Visual Basic .NET allows for a second kind of destructor, named
Dispose, which can be explicitly called at any time to release resources
immediately. Dispose is beyond the scope of this course. For more information
about Dispose, see Object Lifetime: How Objects Are Created and Destroyed
in the Visual Studio .NET documentation.
21
This lesson describes how to use shared data members and shared methods.
You can use shared members for counters or for any common data or common
methods required by all instances of a class.
Lesson agenda
Lesson objectives
22
Class
Class SavingsAccount
SavingsAccount
Public
Public Shared
Shared InterestRate
InterestRate As
As Double
Double
Public
Name
As
String,
Balance
Public Name As String, Balance As
As Double
Double
.. .. ..
End
End Class
Class
SavingsAccount.InterestRate
SavingsAccount.InterestRate == 0.03
0.03
In Visual Basic .NET, you can use shared data members to allow multiple
instances of a class to refer to a single class-level variable.
Syntax
Access levels
Shared data members are directly linked to the class, and you can declare them
as public or private. If you declare data members as public, they are accessible
to any code that can access the class. If you declare data members as private,
you provide public shared properties to access the private shared property.
Example
The following example shows how to create a savings account class that uses a
public shared data member to maintain interest rates for a savings account:
Class SavingsAccount
Public Shared InterestRate As Double
Public Function CalculateInterest( ) As Double
...
End Function
End Class
The value of the InterestRate data member of the SavingsAccount class can be
set globally regardless of how many instances of the class are in use. This value
is then used to calculate the interest on the current balance.
23
After you create a class that uses public shared data members, you can call the
data members of that class from a client application. The following code shows
how to call the SavingsAccount class and its data members from a client
application:
Sub Test( )
SavingsAccount.InterestRate = 0.03
Dim myAccount As New SavingsAccount( )
Dim yourAccount As New SavingsAccount( )
MessageBox.Show(myAccount.CalculateInterest( ))
MessageBox.Show(yourAccount.CalculateInterest( ))
End Sub
Shared properties
You can also create shared properties in your classes. The following example
shows how to declare a shared property called Rate in the SavingsAccount
class:
Class SavingsAccount
Private Shared interestRate As Double
Shared Property Rate( ) As Double
Get
Return interestRate
End Get
Set(ByVal Value As Double)
interestRate = Value
End Set
End Property
End Class
Calling shared
properties from a client
After you declare the shared property Rate, you can use it in a client application
instead of directly accessing the shared data member interestRate. You can call
a shared property by qualifying it either with the class name or with the variable
name of a specific instance of the class.
The following code shows how to call a shared property by qualifying it with
the class name:
SavingsAccount.Rate = 0.03
The following code shows how to call a shared property by using the variable
name of a specific instance of the class:
myAccount.Rate = 0.04
24
'' TestClass
TestClass code
code
Public
Public Shared
Shared Function
Function GetComputerName(
GetComputerName( )) As
As String
String
...
...
End
End Function
Function
'' Client
Client code
code
MessageBox.Show(TestClass.GetComputerName(
MessageBox.Show(TestClass.GetComputerName( ))
))
You can use shared procedure members to design functions that can be called
without creating an instance of the class. Shared procedures are class methods
that are not associated with a specific instance of a class. Shared procedure
members can only access data that is marked with the Shared keyword. For
example, a shared method cannot refer to an instance member of a class.
Example of using a
shared procedure
member
Also note that, in the above code, Show is a shared method of the MessageBox
class.
25
Create a class
"
"
26
The solution files for this practice are located in the install_folder\Practices\
Mod07\SharedMethod\Solution folder.
27
You can add functionality to the classes in the Microsoft .NET Framework or to
your own classes by using inheritance and polymorphism. This lesson describes
inheritance and polymorphism. This lesson also compares classes to structures.
Lesson agenda
Lesson objectives
What Is Inheritance?
What Is Polymorphism?
Explain namespaces.
28
What Is Inheritance?
!
Examples:
Base Class
"
"
Derived Classes
Person
Customer
Employee
Definition
Example of inheritance
Imagine three classes: Customer, Employee, and Person. The attributes and
operations of the Person base class can be applied to Customer or Employee
too. Reusing these attributes and operations is an efficient technique.
Visual Basic .NET supports single inheritance at the class level. That is, a class
can only inherit from a single base class. This is shown in the example in the
previous illustration. Other languages, such as C++, allow a class to inherit
from multiple classes.
29
Keywords
"
"
"
In Visual Basic .NET, you can use inheritance to derive a class from an existing
base class. The derived class can inherit all the base class properties, methods,
data members, events, and event handlers, making it easy to reuse the base class
code throughout an application.
Inherits keyword
You use the Inherits keyword to define a derived class that will inherit from an
existing base class.
Example
Note You can use the MyBase keyword to call methods in a base class when
you are overriding methods in a derived class. You can also use the MyBase
keyword to call the base class constructor and destructor in your derived class.
30
NotInheritable keyword
You use the NotInheritable keyword to define a class that cannot be used as a
base class for inheritance. A compiler error is generated if another class
attempts to inherit from this class.
Example
MustInherit keyword
You use the MustInherit keyword to define classes that are not intended to be
used directly as instantiated objects. The resulting class must be inherited as a
base class for use in an instantiated derived class object.
Example
If the client code attempts to create an instance of this type of class, a compiler
error is generated, as shown in the following example:
' Client code
' The following line generates a compiler error
Dim x As New BaseClass( )
Protected keyword
You use Protected access to limit the scope of a property, method, data
member, event, or event handler to the defining class and any derived class
based on that base class.
Example
31
What Is Polymorphism?
!
CountyTax
CountyTax
CityTax
CityTax
CalculateTax(
CalculateTax( ))
CalculateTax(
CalculateTax( ))
Definition
Example of
polymorphism
Suppose you define a class named BaseTax that provides basic functionality
for computing sales tax in a state. Classes derived from BaseTax, such as
CountyTax or CityTax, could implement methods such as CalculateTax.
Polymorphism refers to the fact that the implementation of the CalculateTax
method might be different in each of the derived classes. The county tax rate
might be different from the city tax rate, for example. Any class that inherits
from BaseTax will have a CalculateTax method, but the way that the tax is
actually calculated might vary in each of the derived classes.
32
Classes
Classes
Structures
Structures
Can
Candefine
definedata
datamembers,
members,
properties,
and
properties, andmethods
methods
Support
Supportconstructors
constructorsand
and
member
memberinitialization
initialization
Can
Candefine
definedata
datamembers,
members,
properties,
properties,and
andmethods
methods
No
Nodefault
defaultconstructor
constructororor
member
memberinitialization
initialization
Support
SupportFinalize
Finalizemethod
method
Do
Donot
notsupport
supportFinalize
Finalizemethod
method
Extensible
Extensibleby
byinheritance
inheritance
Do
Donot
notsupport
supportinheritance
inheritance
Reference
Referencetype
type
Value
Valuetype
type
Classes and structures are similar in several ways: both can define data
members, properties, and methods. However, classes provide some advanced
features that you can use.
The following table compares classes to structures.
Classes
Structures
Initialization
Finalize method
Inheritance
Extensible by inheritance.
Data type
33
Example: System.Windows.Forms.Button
To import a namespace:
"
"
Example of a
namespace
To refer to a class by using its fully qualified name, you prefix the class name
with the namespace that contains the class. For example, the fully qualified
name of the Button class is System.Windows.Forms.Button. By using fully
qualified names, you can declare two classes with the same name in different
namespaces without conflict. By default, every executable file you create with
Visual Basic .NET contains a namespace with the same name as your project.
Accessibility
Defining a namespace
In Visual Basic .NET, you use the Namespace statement to define a new
namespace, which encapsulates the classes that you create, as shown in the
following example:
Namespace CompVB
Public Class StringComponent
...
End Class
End Namespace
34
Using a namespace
At the project level, you must include a reference to the dynamic-link library
(DLL) that contains the namespace. In Visual Basic .NET, you use the Imports
statement to import the types contained in the given namespace so that they can
be referenced directly. The following code shows the use of the Imports
statement:
Imports System.Windows.Forms
Public Class Form1
Inherits Form
If you omit the Imports statement, you will need to use the fully qualified
name of the namespace, as shown in the following example:
Public Class Form1
Inherits System.Windows.Forms.Form
35
Review
Write
Create
Interface
Debug
Code
and Deploy
Use Visual
Studio .NET
Access
Data
Debug
and Deploy
Understanding Classes
Inheritance,
Polymorphism, and
Namespaces
3. Write the code to create a public class called Student that has a private
instance data member named testScore of type Integer.
Public Class Student
Private testScore As Integer
End Class
36
4. Write code to add a read-only property called Score to the Student class.
Public Class Student
Private testScore As Integer
Public ReadOnly Property Score( ) As Integer
Get
Return testScore
End Get
End Property
End Class
37
After completing this lab, you will be able to create a derived class that has
methods.
Note This lab focuses on the concepts in this module and as a result may not
comply with Microsoft security recommendations.
Prerequisites
Solution files
Estimated time to
complete this lab:
30 minutes
38
Exercise 1
Creating a Derived Form Class
In this exercise, you will create a derived form class. This class will inherit
from the System.Windows.Forms class. You will add data members, a
method, and a constructor to create a simple form application that displays the
current date and time.
39
Type
Parameters
Initialize
Private Sub
None
2. Create an instance of the Label type by using the New keyword. Your code
should look as follows:
Private Sub Initialize( )
Me.displayTimeLabel = New Label( )
End Sub
Value
BorderStyle
BorderStyle.Fixed3D
Left
104
Top
56
Height
30
Width
130
40
Value
FlatStyle
FlatStyle.Flat
Left
128
Top
104
Text
Date Time
Your completed code for the Initialize method of the Clock class should
look like the following code:
Private Sub Initialize( )
Me.displayTimeLabel = New Label( )
Me.getTimeButton = New Button( )
Me.displayTimeLabel.BorderStyle = BorderStyle.Fixed3D
Me.displayTimeLabel.Left = 104
Me.displayTimeLabel.Top = 56
Me.displayTimeLabel.Height = 30
Me.displayTimeLabel.Width = 130
Me.Controls.Add(displayTimeLabel)
Me.getTimeButton.FlatStyle = FlatStyle.Flat
Me.getTimeButton.Left = 128
Me.getTimeButton.Top = 104
Me.getTimeButton.Text = "Date Time"
Me.Controls.Add(getTimeButton)
End Sub
2. In the constructor, add a call to the base class constructor and the Initialize
method, as follows:
MyBase.New( )
Initialize( )
41