Presentation is loading. Please wait.

Presentation is loading. Please wait.

VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)

Similar presentations


Presentation on theme: "VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)"— Presentation transcript:

1 VB Classes ISYS 573

2 Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties) and behaviors (methods) of the object. For example, a Customer object is an abstract representation of a real customer. Encapsulation: –The combination of characteristics of an object along with its behavior. –Data hiding: Each object keeps its data and procedures hidden and exposes only those data elements and procedures that it wishes to allow outside world to see. –The implementation of a class – in other words, what goes on inside the class – is separate from the class’s interface.

3 Inheritance: –The process in which a new class can be based on an existing class, and will inherit that class’s interface and behaviors. The original class is known as the base class, super class, or parent class. The inherited class is called a subclass, a derived class, or a child class. –Inherited classes should always have an “is a” relationship with the base class. –Reusability Polymorphism: The concept of using a single name for different behaviors. –Overriding: A derived class with a method named the same as a method in the base class is said to override the method in the base class. Overriding allows an inherited class to take different actions from the identically named method in the base class. –Overloading: A class may have more than one methods with the same name but a different argument list (with a different number of parameters or with parameters of different data type), different parameter signature.

4 Advantages of Object-Oriented Programming Reusable objects –A class can be used in multiple projects. –New classes can be created by iheritance. Building-block concept

5 Data Modeling Entity: A person, place, thing, or event about which data is collected and maintained Attributes: Each entity is described by one or more attributes: the properties or characteristics that the user needs to know about it. Relationship: Entities are related to each other in various way. A relationship models business policies stipulating how one instance is related to another instance. Entity-Relationship diagram

6 Object Relationship Model Object: A basic system element that contains data and processes. –Encapsulation –Data hiding (Public, Private) Relationship: –Specialization: IS-A relationship One-way: A programmer is an employee, but an employee is not necessarily a programmer. Inheritance, base classes and derived classes –Composition: HAS-A relationship Classes that are components of other classes. May not be used to relate an attribute to the class that it describes. It is incorrect to say that a CAR HAS-A vehicleID. A Car is composed of a body, an engine, etc.

7 Adding a Class to a Project Project/Add Window Form/Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in the General Declaration section Property procedures: Set / Get –Adding methods –Adding events, exceptions Private variables and procedures can be created for internal use.

8 Anatomy of a Class Module Class Module Public Variables & Property Procedures Public Procedures & Functions Exposed Part Private Variables Private Procedures & Functions Hidden Part

9 Class Code Example Public Eid As String Public Ename As String Public salary As Double Public Function tax() As Double tax = salary * 0.1 End Function

10 Creating Property with Property Procedures Implementing a property with a public variable the property value cannot be validated by the class. We can create read-only, write-only, or write-once properties with property procedure. Steps: –Declaring a private class variable to hold the property value. –Writing a property procedure to provide the interface to the property value.

11 Property Procedure Code Example Public Class Emp2 Public SSN As String Public Ename As String Public DateHired As Date Private hiddenJobCode As Long Public Property JobCode() Set(ByVal Value) If Value 4 Then hiddenJobCode = 1 Else hiddenJobCode = Value End If End Set Get JobCode = hiddenJobCode End Get End Property End Class

12 How the Property Procedure Works? When the program sets the property, the property procedure is called and the code between the Set and End Set statements is executed. The value assigned to the property is passed in the Value argument and is assigned to the hidden private variable. When the program reads the property, the property procedure is called and the code between the Get and End Get statements is executed.

13 Property that Holds an Array of Data Demo: Property with Parameters Public Class ArrayProperty Public eid As String Public ename As String Private hiddenPhone(2) As String Public Property phone(ByVal index As Integer) Get phone = hiddenPhone(index) End Get Set(ByVal Value) hiddenPhone(index) = Value End Set End Property End Class

14 Implementing a Read-Only Property Declare the property procedure as ReadOnly with only the Get block. Ex. Create a YearsEmployed property from the DateHired property: Public ReadOnly Property YearsEmployed() As Long Get YearsEmployed = Now.Year - DateHired.Year End Get End Property –Note: It is similar to a calculated field in database.

15 Implementing a Write-Only Property Declare the property procedure as WriteOnly with only the Set block. Ex. Create a PassWord property: Private hiddenPassword as String Public WriteOnly Property Password() As String Set(ByVal Value As String) hiddenPassword=Value End Set End Property How to create a write-once property?

16 Method Overloading Using the Overloads Keyword Public Overloads Function tax() As Double tax = salary * 0.1 End Function Public Overloads Function tax(ByVal sal As Double) As Double tax = sal * 0.1 End Function

17 Property Overloading Private hiddenPhone(2) As String Private Phone2 As String Public Overloads Property phone(ByVal index As Integer) Get phone = hiddenPhone(index) End Get Set(ByVal Value) hiddenPhone(index) = Value End Set End Property Public Overloads Property phone() Get phone = Phone2 End Get Set(ByVal Value) Phone2 = Value End Set End Property

18 Default Property Defined by using the Default keyword. Can be accessed by using the object name alone. Must have at least one parameter. Cannot be declared as read-only or write- only.

19 Default Property Example Private hiddenPhone(2) As String Default Public Property phone(ByVal index As Integer) Get phone = hiddenPhone(index) End Get Set(ByVal Value) hiddenPhone(index) = Value End Set End Property

20 Constructors and Destructors A constructor is a method that runs when a new instance of the class is created. In VB.Net the constructor method is always named Sub New. A destructor is a method that automatically executes when an object is destroyed.

21 Constructor Example Public Sub New() Me.eid = "" ename = "" salary = 0.0 End Sub Public Sub New(ByVal empId As String, ByVal empName As String, ByVal empSal As Double) eid = empId ename = empName salary = empSal End Sub Note: Cannot use Overloads with the New.

22 Constructors and Read-Only Field A constructor procedure is the only place from inside a class where you can assign a value to read-only fields. – Public ReadOnly currentDate As Date – Public Sub New() – Me.eid = "" – ename = "" – salary = 0.0 – currentDate = Today – End Sub

23 Dereferencing Objects When your program is finished using an instance of an object, you can deferencing the object by setting the variable to the special value Nothing. –classVariableName = Nothing When an object no longer has any references, VB’s garbage collector will remove it from memory. Before the garbage collector removes the variable, it calls the class’s Finalize method.

24 Example of Finalizer Protected Overrides Sub Finalize() MyBase.Finalize() End Sub

25 Shared Methods A shared method is available from a class without the need to create an instance of the class. To create a shared method, include the Shared keyword in the method definition.

26 Shared Method Example Public Class myMath Public Shared Function sum(ByVal x As Double, ByVal y As Double) As Double sum = x + y End Function Public Shared Function difference(ByVal x As Double, ByVal y As Double) As Double difference = x - y End Function End Class

27 Shared Variables A shared variable is one that is shared by all instances of a class. Define the variable with the Shared keyword. –Ex. Shared instanceCount as Integer The default scope for shared variables is private, but they can be declared as Public.

28 Shared Variable Example: Number of Times Instances are Created. Shared instanceCount As Integer Public Sub New() instanceCount += 1 MessageBox.Show(instanceCount.ToString) End Sub Note: How to keep track of the number of active instances. (Testing with Nothing, instanceCount – 1, FormClosed)

29 Creating a Read-Only ID Property for each Instance of a Class Public ReadOnly instanceID As Integer Shared instanceCount As Integer Public Sub New() instanceCount += 1 instanceID = instanceCount End Sub

30 Same ID Property Using Property Procedure Shared instanceCount As Integer Public Sub New() instanceCount += 1 End Sub Public ReadOnly Property instanceID() As Integer Get instanceID = instanceCount End Get End Property

31 Class Events Events that class can raise. Different from user events such as mouse clicks, these events are triggered in code in the class and can be detected by the host program. An event is declared in a class definition using the Event keyword. The event declaration statement declares the name of the event and types of arguments that the event has. –Public Event EventName(Argument list) To raise an event, use the RaiseEvent statement: –RaiseEvent EventName(Argument List)

32 Trapping Events with WithEvents To trap class events, declare a class variable with the WithEvents keyword. –Dim WithEvents emp1 As New emp() Create a event procedure to response to the event: –Every event procedure has a Handles keyword to identify the event it handles. The name of a event procedure is meaningless. Private Sub emp1_calTax() Handles emp1.calTax

33 Class Events Example Public Class emp Event calTax() Event readID() Public Function tax(ByVal salary As Double) As Double tax = salary * 0.1 RaiseEvent calTax() End Function Public ReadOnly Property instanceID() As Integer Get instanceID = instanceCount RaiseEvent readID() End Get End Property

34 Dim WithEvents emp1 As New emp() Private Sub emp1_calTax() Handles emp1.calTax MessageBox.Show("tax calculated") End Sub Private Sub emp1_readID() Handles emp1.readID MessageBox.Show("read id") End Sub

35 Create a Student Class to Process Student File Student Class: –Properties: Sid, Sname, GPA –Methods OpenInputFile ReadNext AppendNew CloseFile –Other property: NotEmpty

36 Public Class Student Dim fileNumber As Integer Public sid As String Public sname As String Public gpa As Double Private hiddenNotEmpty As Boolean Public ReadOnly Property NotEmpty() Get NotEmpty = hiddenNotEmpty End Get End Property Public Sub openInputFile() fileNumber = FreeFile() FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input) If Not EOF(fileNumber) Then Input(fileNumber, sid) Input(fileNumber, sname) Input(fileNumber, gpa) hiddenNotEmpty = True Else hiddenNotEmpty = False End If End Sub

37 Public Sub ReadNext() If Not EOF(fileNumber) Then Input(fileNumber, sid) Input(fileNumber, sname) Input(fileNumber, gpa) hiddenNotEmpty = True Else hiddenNotEmpty = False End If End Sub Public Sub AppendNew() FileClose(fileNumber) fileNumber = FreeFile() FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Append) WriteLine(fileNumber, sid, sname, gpa) FileClose(fileNumber) End Sub

38 Public Sub ReCycle() FileClose(fileNumber) fileNumber = FreeFile() FileOpen(fileNumber, "c:\stdata.txt", OpenMode.Input) If Not EOF(fileNumber) Then Input(fileNumber, sid) Input(fileNumber, sname) Input(fileNumber, gpa) hiddenNotEmpty = True Else hiddenNotEmpty = False End If End Sub Public Sub CloseFile() FileClose(fileNumber) End Sub

39 Add events: –FileOpen, FileClose events Add constructors –Sub New() –Sub New(arguments) Allow user to choose files.

40 Enumerations Provide a way to associate meaningful names with a sequence of constant values. Define an enumeration using an Enum statement. –Enum seasonOfYear –Spring = 1 –Summer = 2 –Fall= 3 –Winter = 4 –End Enum

41 Using Enum to Choose Files Public Class Student Enum Files student1 student2 End Enum Dim fileName As String Dim fileNumber As Integer Public sid As String Public sname As String Public gpa As Double Private hiddenNotEmpty As Boolean End Sub

42 Dim st As New Student() Private Sub frmStudent_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If InputBox("enter 1 for file1, 2 for file 2") = 1 Then st.openInputFile(Student.Files.student1) Else st.openInputFile(Student.Files.student2) End If


Download ppt "VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)"

Similar presentations


Ads by Google