Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

Object.Method

In the preceding syntax, Object refers to the name of the object and Method refers to the method that you need to access.

Note You might not want the properties and methods of an object to be accessed by the code outside the class. For this you declare the members of a class by using the Private statement. However, if you want the properties and methods to be accessible outside the class, use the Public statement to declare them. Public members become part of an object's interface.

Events

In addition to properties and methods, an object can have an event associated with it. Events are actions or occurrences that are detected by a program. They are responsible for giving indications to other objects and code about what is going on. An action, such as a user clicking the mouse or pressing a key on the keyboard, can be an event. System occurrences, such as a system running out of memory, can also be categorized as an event. The following statements and keywords help you in raising and handling events:

§The Event keyword helps you to declare an event. The following syntax is used to declare an event:

§'Declare an event

Event MyEvent

§The RaiseEvent statement is used to generate or raise an event. The following syntax is used to raise an event:

§'Raise the event

RaiseEvent MyEvent

§The WithEvents statement is used to declare a reference to an object that may be raising events:

§'Declare an object of the class employee

Dim WithEvents EmpObj As Employee

§The Handles statement specifies the event handled by an event handler. An event handler (or event procedure as used with VB6 terminology) is a procedure that is invoked when the event occurs:

§'Declare an event handler

§Sub MyEve ntHandler() Handles EmpObj.MyEvent

VB.NET provides you with a set of classes that you can use to accomplish various tasks in your application. However, there might be certain tasks, which cannot be accomplished with the already existing classes. For example, consider a situation wherein you want to develop an application that handles all transactions related to salary, leave, and performance assessment of employees in an organization. In such a situation, you are required to create your own class to achieve the desired functionality. VB.NET gives developers the opportunity to put their creative and logical brains to the best use by allowing them to create their own classes instead of using the existing ones. Let us now look at some of the features of OOP.

Features of object-oriented programming

The objects in an object-oriented program support encapsulation, polymorphism, and reuse. In VB.NET, the best way to accomplish reuse is by inheritance. In VB6, reuse was partially implemented with delegation. Let us now look at the concepts related to objectoriented programming.

Encapsulation

Encapsulation is a key concept in OOP. Encapsulation means data hiding, which implies that methods and properties of an object cannot be accessed directly by any code outside the class. Objects prevent this code from accessing the data unless the data has been made available using properties or methods. The calling code isn't aware of how the data is being stored in the object.

To understand encapsulation better, consider a class named Employee. The Employee class contains two properties, EmpCode and EmpName. In your application, you need to write code to manipulate the details of employees. To do so, you need to create an object of the Employee class. The object then retrieves the data for the code, and the code acts upon it. But the code simply doesn't know from where and how the data was retrieved.

Polymorphism

Polymorphism is the ability to define multiple classes having similar methods or properties. These methods or properties might perform different functions and can be used interchangeably by the client code.

To understand polymorphism better, consider a class named Employee, which contains a method named Department. If you create a new class, FullTimeEmployee, derived from the Employee class, you can override the method Department. However, this method might be completely different from the method in the base class.

Let us now implement the concept of polymorphism in the following example. Best Products, Inc. needs to calculate bonuses for its team members and team leaders based on their monthly salaries. The bonus for team members and team leaders is 5 percent and 10 percent of their monthly salary, respectively. Now, we will create one class each for team members and team leaders, and one wrapper class that will calculate the amount of bonus for both team members and team leaders. To do so, you will use the following code:

'Class : clsTeamMembers

Const BonusRate As Double = .05

Public Function CalcBonus ( dblSalaryValue as Double) as Double

CalcBonus = BonusRate * dblSalaryValue

End Function

'Class : clsTeamLeaders

Const BonusRate As Double = .10

Public Function CalcBonus ( dblSalaryValue as Double) as Double

CalcBonus = BonusRate * dblSalaryValue

End Function

'Class : clsBonus

'The private member variables

Private strDesignation As String

Private oTeamMembers As clsTeamMembers

Private oTeamLeaders As clsTeamLeaders

Public Sub New ()

Dim oTeamMembers As New clsTeamMembers ()

Dim oTeamleaders As New clsTeamLeaders ()

End Sub

Public Function calcBonus (dblSalaryValue as Double) as Double

'Calculate Bonus based on designation of the employee

If strDesignation = "TM" then

CalcBonus = oTeamMembers.CalcBonus (dblSalaryValue)

Else

CalcBonus = oTeamLeaders.CalcBonus (dblSalaryValue)

End If

End Function

In the preceding code, the following classes appear:

§clsTeamMembers: Calculates the bonus for team members. The bonus rate has been specified as 0.05 (5 percent).

§clsTeamLeaders: Calculates the bonus for team leaders. The bonus rate has been specified as 0.1 (10 percent).

§clsConveyance: Used as a wrapper class, wherein you just need to specify the designation, and the amount of bonus will calculate automatically. This class references both the previously created clsTeamMembers and clsTeamLeaders classes.

The method used in the clsBonus class gives different results based on the designation. Instead of creating separate objects for the clsTeamMembers and clsTeamLeaders classes to calculate the bonus, you simply need to create one object of the clsBonus class and it will give results based on the designation. Hence, the object of the clsBonus class is a good example of using polymorphism.

Inheritance

Inheritance includes the concept of base class and derived class. The base class is the existing class and the derived class is the new class that is derived from the base class. Derived classes are also called child classes. Inheritance saves you time and effort by reusing the existing code.

Inheritance is transitive in nature. In other words, consider a class called Employee derived from a class called Individual, which in turn is derived from a class called Human Being (see Figure C-1). In this case, the class Employee will inherit the members (methods and properties) declared in the class Individual as well as the class Human Beings. The Employee class can also override the inherited members. Overriding inherited members means that the definition of these members can be changed in the child class depending on the requirement. In addition, the Employee class can create its own members.

Figure C-1: The class hierarchy

In Visual Basic .NET, the following statements and modifiers have been introduced to support inheritance:

§Inherits: This statement is used to specify the class (base class) from which the current class inherits. The following code illustrates the use of the Inherits statement:

§'Declare a class named Employee

§Class Employee

§

§'Specify the base class as Individual Inherits Individual

§NotInheritable: This modifier is used to specify that the class cannot be used as a base class. In other words, classes cannot be derived from a class. The following code statement illustrates the use of the NotInheritable modifier:

§'Declare a class named Employee

§NotInheritable Class Employee

This statement declares the class Employee as NotInheritable, which means that you cannot derive a class from this class.

§MustInherit: This modifier is used to specify that the instances of the class cannot be created. You can use the class only when you inherit from it:

§'Declare a class named Employee

MustInherit Class HumanBeing

This statement declares the class HumanBeing as MustInherit, which means that you cannot create instances of this class and you need to create classes derived from this class.

Developers often get confused about when to use inheritance and when to avoid using it. Though inheritance is a very useful concept in Visual Basic programming, developers should know when to use it. The following list gives a brief description of the situations in which you can use inheritance:

§When the code can be reused from the base classes.

§When you need to apply an existing class and methods to different data types.

§When you want the global changes to be reflected in child classes when you change a base class.

Creating and Using Classes

In the previous section, you learned the concepts of OOP. You will now learn how to create and use classes. The six steps to create and use classes are explained in the sections that follow.

Step 1: Develop a VB Web application

To begin creating a class, you first need to have a new Visual Basic application in place. In this case, you will develop a Visual Basic Web application. To do so, complete the following steps:

1.Select File New Project to open the New Project dialog box.

2.In the New Project dialog box, select Visual Basic Project in the left pane and select ASP.NET Web Application in the right pane.

3.Specify a name for the new project, if necessary, and click OK.

4.Change the File Name property of the form WebForm1.aspx to EmployeeDetails.aspx.

Step 2: Design the form

Design the form as shown in Figure C-2 and name the controls on the form as shown in Table C-1.

Figure C-2: A sample Web application form

 

Table C-1: Name of the controls on the EmployeeDetails form

 

 

 

 

 

 

 

 

 

 

 

 

Control

 

 

Contains

 

 

Name

 

 

 

 

 

 

 

 

 

 

 

TextBox

 

 

Employee

 

 

TxtEmpCode

 

 

 

 

 

Code

 

 

 

 

 

 

 

 

 

 

 

 

TextBox

 

 

Employee

 

 

TxtEmpName

 

 

 

 

 

Name

 

 

 

 

 

 

 

 

 

 

 

 

TextBox

 

 

Designation

 

 

TxtDesg

 

 

 

 

 

 

 

 

 

TextBox

 

 

Department

 

 

TxtDept

 

 

 

 

 

 

 

 

 

TextBox

 

 

Salary

 

 

TxtSalary

 

 

 

 

 

 

 

 

 

Button

 

 

Show

 

 

BtnShow

 

 

 

 

 

Details

 

 

 

 

 

 

 

 

 

 

 

 

Button

 

 

Calculate

 

 

BtnCalc

 

 

 

 

 

Deduction

 

 

 

 

 

 

 

 

 

 

 

 

DropDownList

 

 

Employee

 

 

LstCategory

 

 

 

 

 

Category

 

 

 

 

 

 

 

 

 

Note

Also add the items Employee and Trainee to lstCategory. You can

 

 

 

do so by using the Items property of the control.

 

 

Step 3: Create a class

Now you need to create a class named Employee. To do so, complete the following steps:

1.Select Project Add Class.

2.Specify the name of the class as Employee. This will open a code window (Employee.vb).

3.In this code window, you can add your own code to specify properties and methods of this class. The class appears as shown in Figure C-3.

Figure C-3: A newly created class

Step 4: Add properties to the class

An employee will be having a number of properties, such as name, designation, and department. Therefore, the next thing you need to do is to add properties to the Employee class. Adding properties is one of the simplest things you can do in Visual Basic. For the sample form created in our example, the different employee details include Employee Code, Employee Name, Employee Designation, Employee Department, and Employee Salary. You can use these as the properties of the Employee class.

Before proceeding further, let's first understand the steps involved in creating a property.

1.You need to declare the property. You do this by using the Property statement. The Property statement also declares the procedure to assign and read values to and from a property. These procedures are referred to as property procedures. The following is the syntax of the Property statement:

2.'Declare a property along with its data type

Property PropertyName () As DataType

3.You need to assign values to a property. To do so, you use the Set statement, which declares the Set property procedure. This procedure is called when ever a change in property value occurs. The Set procedure takes the value (of the property) to be set as a parameter. The syntax is as follows:

4.'Use the Set statement to return the property value

5.Set (ByVal value As Type)

6.ClassVariable = value

7.End Set

8.You need to read value stored in a property. To do so, you use the Get statement, which declares the Get property procedure. This procedure can return the value of a property either by using the Return keyword or by assigning the value to the property:

9.'Use the Get statement to return the property value

10.Get

11.PropertyName = ClassVariable

12.

13.'The above statement can be replaced by following statement

14.Return ClassVariable

15.

End Get

Now that you know the steps involved in creating a property, you need to create properties for the Employee class that you created. To create the properties, type the following code in the Employee.vb page between Class and End Class statements:

'Declare the variables used in the class

Dim EmpCode, EmpName, EmpDept, EmpDesg, EmpSal As String

Property EmployeeCode() As String

Get

EmployeeCode = EmpCode

End Get

Set(ByVal Value As String)

EmpCode = value

End Set

End Property

Property EmployeeName() As String

Get

EmployeeName = EmpName

End Get

Set(ByVal Value As String)

EmpName = value

End Set

End Property

Property EmployeeDesig() As String

Get

EmployeeDesig = EmpDesg

End Get

Set(ByVal Value As String)

EmpDesg = value

End Set

End Property

Property EmployeeDept() As String

Get

EmployeeDept = EmpDept

End Get

Set(ByVal Value As String)

EmpDept = value

End Set

End Property

Property EmployeeSal() As String

Get

EmployeeSal = EmpSal

End Get

Set(ByVal Value As String)

EmpSal = value

End Set

End Property

Note

Notice the code to create properties. Here, you create a property

 

by using the Get and Set assessors within the Property. So, the

 

separate Get, Set, and Let statements to create a property in VB6

 

are gone with the release of VB.NET.

In this code, the properties EmployeeCode, EmployeeName, EmployeeDesig, EmployeeDept, and EmployeeSal have been created.

Step 5: Create methods

After creating properties of a class, you might need to perform certain operations on these properties, such as displaying data. For this, you create methods in your class. In the Employee class, you need to add a method that displays the values stored in the properties. To do so, add the following code to the class:

Public Function Display(ByVal strCode As String, ByVal

strName As String, ByVal strDesig As String, ByVal strDepart As

String, ByVal strSal As String) As String

Dim strDetail As String

strDetail = "Employee code " + strCode + " Name " +

strName + " Designation " + strDesig + " Department " + strDepart

+ " Salary " + strSal

Return strDetail

End Sub

In the following code, the function DisplayDeduction calculates the deduction based on salary. When the user enters his/her salary in the txtSalary text box, the amount of deduction will be automatically calculated and displayed on the screen.

The DisplayDeduction method takes a String argument, which is the value entered in the txtSalary text box. The value passed as argument (a String value) is converted to Integer datatype. Then, the deduction is calculated and is stored in a variable of Double datatype. Finally, the method returns the calculated deduction.

Public Function DisplayDeduction(ByVal strSal As String) As Double

Dim intSal As Integer

intSal = CType(strSal, Integer)

Dim dblDedn As Double

dblDedn = intSal * 0.1

DisplayDeduction = dblDedn

End Function

Step 6: Implement the class functionality

After creating the Employee class, you need to implement the functionality of this class in your form. This step instructs you on using the methods of the Employee class in your form. As shown in Figure C-2, the form has two buttons with captions Show Details and Calculate Deduction. To associate the desired functionality with the button labeled Show Details, you'll use the Display method of the Employee class. To do so, double-click the Show Details button. This displays the Click event of the button.

Now, type the following code in this event:

'Declaring and initializing the object of the Employee class

Dim Emp As New Employee()

'Setting the properties of the Employee class

Emp.EmployeeCode = txtEmpCode.Text

Emp.EmployeeName = txtEmpName.Text

Emp.EmployeeDesig = txtDesg.Text

Emp.EmployeeDept = txtDept.Text

Emp.EmployeeSal = txtSalary.Text

'Calling the Display method of the Employee class

lblInfo.Text = Emp.Display(Emp.EmployeeCode, Emp.EmployeeName, Emp.EmployeeDesig, Emp.EmployeeDept, Emp.EmployeeSal)

In this code:

§Emp is the object of the Employee class.

§The properties of the object have been set to values entered by a user in the different text boxes in the form.

§While calling the Display method, the different properties have been passed as parameters.

Similarly, double-click the Calculate Deduction button on your form to edit the code in the Click event of this button. Now, type the following code to add functionality to this button:

'Declaring and initializing the object of the Employee class

Dim Emp As New Employee()

'Declaring a String variable

Dim strSal As String

'Declaring a variable of Double data type to hold the value

returned from the DisplayDeduction method

Dim dblRetValue As Double

'Initializing the String value with the value entered in a text box

strSal = txtSalary.Text

'Calling the method of the Employee class

dblRetValue = Emp.DisplayDeduction(strSal)

'Displaying the return value of the method in the label

lblDedn.Text = CType(dblRetValue, String)

After doing all six steps, you need to test the application you created. For this, execute the code and enter any values you want. Now, click the Show Details button, and the details of the employee appear in the label lblInfo. Then, click the Calculate Deductions button, and the deduction for the employee appears in the label lblDedn, as shown in Figure C-4.

Figure C-4: The sample output

Creating an Object Hierarchy with Inheritance

We have already discussed the concept of inheritance in the earlier section. In this section, you will learn how to implement inheritance. The steps for creating an object hierarchy with inheritance are simple:

1.Create the base class with all the required members.

2.Create a child class that inherits from the base class.

3.In the child class, you can use the members of the existing class, override these members, or declare new members.

Consider the application that you created earlier. You had created a class called Employee. Now, you will create another class called Trainee. You will treat the Employee class as the base class and use inheritance to override its methods. The four steps to achieve this are provided in the following sections.

Step 1: Create a child class

In our example, the first step would be to create a child class, because the base class already exists. To create a new class, complete the following steps.

1.Select Project Add Class.

2.Specify the name of the class as Trainee. A new code window (Trainee.vb) opens.

3.Inherit the Trainee class from the base class Employee. To do so, add the following code to the Trainee class.

4.Public Class Trainee

5.

6. Inherits Employee

7.

Соседние файлы в папке c#