Title: Chapter 1: Classes
1Chapter 1 Classes
2Overview
- Introduction
- Value Types and Reference Types
- Object-Oriented Design
- Creating Classes
- Properties
- Constructors
- Multi-Tier Applications
- Composition Relationships
- Nested (Inner) Classes
- Using Text Files
31.1 Introduction
- Object-Oriented Programming (OOP)
- A class is a pattern or blueprint
- defines group of related objects with common
characteristics - identifies a specific data type
- Attributes and behaviors
41.2 Value Types and Reference Types
- Value type
- variable that contains its own data
- primitives, such as Integer, Single, Decimal
- Reference type
- contains a reference to another memory location
- objects and arrays, including strings
5Value Type
Dim temp As Integer mCount
temp 40 'mCount still equals 25
6Reference Type
S1 New Student S1.Name "Fred Smith"
7Assigning Reference Types
- Dim tests() As Integer 80, 95, 88, 76, 54
- Dim scores() As Integer tests
8Life and the Garbage Collector
- Lifetime of an object is determined by...
- whether or not references to it still exist
- Object with no references is unreachable
- Unreachable object can be reclaimed by the
garbage collector
9Namespaces
- A namespace groups one or more classes under a
common name - Avoids collisions between identical class names
- Good for
- large applications
- groups of programmers
- Every VB project has a root namespace
101.3 Object-Oriented Design
- Object-Oriented Analysis
- detailed specification of the problem
- find classes that reflect the application domain
- Object-Oriented Design
- create classes that cooperate and communicate
11Design Steps
- Find the classes
- physical entities in the application domain
- control structures
- Describe the classes
- attributes characteristics (properties)
- operations actions the class may perform
(methods)
12Interface and Implementation
- Interface
- visible portion of a class
- Implementation
- hidden from client programs
- private members
- encapsulation principle
13Inheritance
- A derived class inherits characteristics of an
existing class - GradStudent and StudentEmployee are derived
classes
14Clients and Servers
- A server produces information consumed by client
- Client creates a reference to the server and
sends requests via method calls - Server sends responses via method return values
151.4 Creating Classes
- Class declaration syntax
- Public Class classname
- member-declarations
- End Class
- Example
- Public Class Student
- Private id As String
- Public New( ) ...
- End Class
16Hands-On Tutorial
- Title Student Class
- Program name Student1
- Creates a Student class
- Retrieves and displays values of member variables
(fields) - Output
17Methods
- A method is a procedure declared inside a class
- sub procedure
- function procedure
- Example
- Public Class Student
- . . .
- Private Sub Print()
- MessageBox.Show(mID ", " mName _
- ", " mAge)
- End Sub
- End Class
18Hands-On Tutorial
- Adding the GetGradeAverage method
- Program name Student1
- Public mCreditsEarned As Single
- Public mTotalGradePoints As Single
- Public Function GetGradeAverage() As Single
- Return mTotalGradePoints / mCreditsEarned
- End Function
19Public and Private Member Access
- Public member
- accessible to entire program
- Private member
- invisible outside the enclosing class
- Fields should be private
- Methods can be public or private
201.5 Properties
- Property procedures
- act like variables to clients
- Visual Studio .NET creates a template
- General format
- Public Property name() As type
- Get
- End Get
- Set(ByVal Value As type)
- End Set
- End Property
21Age Property Example
- Public Property Age() As Integer
- Get
- Return mAge
- End Get
- Set(ByVal Value As Integer)
- If Value gt 1 And Value lt 130 Then
- mAge Value
- End If
- End Set
- End Property
22ReadOnly Properties
- Can be read, but not modified by clients
- Use ReadOnly qualifier
- Example
- Public ReadOnly Property GradePointAverage() As
Single - Get
- If mCreditsEarned ltgt 0 Then
- Return mTotalGradePoints / mCreditsEarned
- Else
- Return 0.0
- End If
- End Get
- End Property
23Hands-On Tutorial
- Title Adding Properties to the Student Class
- Program name Student2
- Adds the following properties
- ID
- Name
- Age
- CreditsEarned
- GradeAverage
24Shared Variables
- Contains data that is shared among all class
instances - Also called a shared field
- Program example SharedMembers
- Usually private
- Example
- Private Shared mInstanceCount As Integer 0
25Shared Properties
- Sets/returns value of shared variable
- Usually public
- Example
- Public Shared ReadOnly Property InstanceCount() _
- As Integer
- Get
- Return mInstanceCount
- End Get
- End Property
261.6 Constructors
- Methods that run automatically when an instance
of a class is created - Always named New
- Can be overloaded
- each must have different parameter list
- Default constructor example
- Public Sub New()
- mID "000000000"
- mName "(unknown)"
- End Sub
27Overloading the Constructor
- Public Sub New(ByVal id As String, ByVal name As
String, _ - ByVal age As Integer)
- mID id
- mName name
- mAge age
- End Sub
- 'Sample call
- Dim s2 As New Student("222222222", "Julio
Gonzalez", 23)
28Optional Constructor Parameters
- Optional keyword lets you avoid overloading the
constructor - You must supply default arguments
- Public Sub New( _
- Optional ByVal id As String "000000000", _
- Optional ByVal name As String "(unknown)", _
- Optional ByVal age As Integer 0)
- mID id
- mName name
- mAge age
- End Sub
29Hands-On Tutorial
- Title Adding a Parameterized Constructor to the
Student Class - Student3 program
301.7 Multi-Tier Applications
- Multi-tier application model
- Design Patterns (1995) by Erich Gamma, Richard
Helm, and others - Three layers, or tiers
- presentation
- business
- data
31Three Tiers (Layers)
- Presentation
- Interacts with the user, provides all
input-output - Business
- Contains processing rules and logic, including
behaviors and attributes belonging to application
entities - Data
- Information storage and retrieval system, such as
Database connections, recordsets, text files, and
XML data
32Hands-On Tutorial
- Title Bank Teller Application
- Program BankTeller
- Presentation tier
- frmTeller class
- Business/Data tier
- Account class
33Hands-On Tutorial
- Title Bank Teller Transaction Log
- Program BankTeller2
- Presentation tier
- frmTeller class
- Business tier
- Account class
- Data tier
- TransactionLog class
- logs all transactions to a file
341.8 Composition Relationships Between Classes
- Created when one class contains fields that are
instances of other classes - Also known as aggregation, or containing
relationship
35Employee Information Example
- clsEmployee class contains objects of the
following types - clsPersonalInfo
- clsAddress
- clsSalaryItem
- clsProject
36Using UML to Describe Classes
UML stands for Universal Modeling Language
37Overriding ToString
- Standard way of displaying the state of an object
- Example
- Public Overrides Function ToString() As String
- Return mStreet ", " _
- mCity ", " _
- mState ", " _
- mZip ", " mPhone
- End Function
38Hands-On Tutorial
- Title Employee Information
- Program EmployeeInfo
- Uses the clsEmployee, clsPersonalInfo,
clsAddress, clsSalaryItem, and clsProject classes
391.9 Optional Topic Nested (Inner) Classes
- A nested class is declared inside an existing
class - Good way of hiding a class
- Prevents name clashes with other classes having
the same name - Class NetworkConnection
- Class Address
- Private mURL(3) As Integer
- End Class
- End Class
401.10 Optional Topic Using Text Files
- Advantages
- save and retrieve information without the
overhead of a database - platform independent
- edit with any text editor
- Required Imports
- System.IO
- System.IO.File
41Text File Examples - 1
- Find out if a text file exists
- If Exists("input.txt") Then ...
- Open a text file for reading
- Dim inFile As StreamReader OpenText("input.txt")
- Create a new text file
- Dim outFile As StreamWriter CreateText("output.t
xt") - Append to an existing text file
- Dim outFile As StreamWriter AppendText("output.t
xt")
42Text File Examples - 2
- Read a line from a text file
- Dim temp As String
- temp inFile.ReadLine()
- Check for end of file
- While inFile.Peek ltgt -1
- temp inFile.ReadLine()
- End While
- Write a line to a text file
- Dim temp As String "Some data"
- outFile.WriteLine(temp)
- Close a StreamReader or StreamWriter
- inFile.Close()
43The End