Transcript Welcome to

Chapter 4
Introduction to Classes & Objects
7/20/2015
VBN2008-04
1
Quotes for Today
You will see something new. Two things.
And I call them Thing One and Thing
Two.
Dr. Theordor Seuss Geisel
Nothing can have value without being an
object of utility.
Karl Marx
7/20/2015
VBN2008-04
2
Classes
Properties, Methods, &
Constructors
7/20/2015
VBN2008-04
3
Methods & Attributes
• Method represents task in a program
– Describes the mechanisms that actually
perform its tasks
– Hides from its user the complex tasks that
it performs
– Method same as a Procedure
• Classes contain one or more attributes
– Specified by instance variables
– Carried with the object as it is used
7/20/2015
VBN2008-04
4
Class
• Is a blueprint or template for one or
more objects
• Defines what the object can do
• Plenty of pre-defined classes available in
Visual Basic
– Ex.
7/20/2015
System.Math
System.Windows.Forms.Form
VBN2008-04
5
Object
• Is a user interface element
• Can be created on VB form using control
in Toolbox
• Forms are objects
• Inherit functionality from their class
7/20/2015
VBN2008-04
6
Method
• Is a special statement that performs an
action or a service for a particular object
– Syntax Object.Method(Value)
– Example
Math.Min(3,5)
Math.Min(Math.Min(3,5),4)
7/20/2015
VBN2008-04
7
Methods cont
• Any class or module that contains a Main method can
be used to execute an application
• Visual Basic is extensible
– Programmers can create new classes
• Class instance creation expression
– Keyword New
– Then name of class to create and add parentheses
• Calling a method
(Class.Method)
– Object’s name, then dot separator (.)
– Then method’s name and parentheses
7/20/2015
VBN2008-04
8
Example of Method
' Fig. 4.1: GradeBook.vb
' Class declaration with one method.
Public Class GradeBook
‘ Method Header
' display a welcome message to the GradeBook user
Public Sub DisplayMessage()
Console.WriteLine("Welcome to the Grade Book!")
End Sub ' DisplayMessage
When Method is
End Class ' GradeBook
called, it is output to
screen
7/20/2015
VBN2008-04
9
UML Diagramming
• Unified Modeling Language
– Developed by the “three amigos”:
• Grady Booch – Booch Method
• James Rumbaugh – OMT (Object Modeling Technique)
• Ivar Jacobson – OOSE (Object-Oriented Software
Engineering)
7/20/2015
VBN2008-04
10
UML Two Goals
• Provide consistency in giving feedback to
project sponsor that the problem domain
is well understood.
• Provide a consistent model for proper
software implementation.
• Based on Synergy Model
7/20/2015
VBN2008-04
11
UML 9 Diagrams
Activity
Class
Collaboration
Some also
Include
Class
Component
Deployment
Use Case
Use Case
Sequence
7/20/2015
State
VBN2008-04
Sequence
12
UML Class Diagrams
• Top compartment
– name of class
• Middle compartment
– class’s attributes or instance variables
• Bottom compartment
– Class’s operations or methods
– Plus sign indicates Public modifier
7/20/2015
VBN2008-04
13
Example of UML Diagram
• Indicates that class GradeBook has a
public DisplayMessage operation.
7/20/2015
VBN2008-04
14
Declaring Methods
• Method parameters
– Information passed to method
– Called arguments
– Supplied in the method call
• Input method
– Reads line of input - Console.ReadLine
– Dim nameOfCourse As String = _
Console.ReadLine()
7/20/2015
VBN2008-04
15
Method with Parameter
• Parameters specified in method’s
parameter list
– Part of method header
– Uses a comma-separated list
More about
– Keyword ByVal
ByVal &
• The argument is passed by value
7/20/2015
VBN2008-04
ByRef later
16
UML Example
• indicates that class GradeBook has a
DisplayMessage operation with a
courseName parameter of type String.
7/20/2015
VBN2008-04
17
Instance Variables
& Properties
• Variables declared in the body of method
– Called local variables
– Can only be used within that method
• Variables declared in a class declaration
– Called fields or instance variables
– Each object of the class has a separate
instance of the variable
7/20/2015
VBN2008-04
18
Example
' Fig. 4.7: GradeBook.vb
' GradeBook class that contains instance variable courseNameValue
' and a property to get and set its value.
Public Class GradeBook
Private courseNameValue As String ' course name for this GradeBook
' property CourseName
Public Property CourseName() As String
Get ' retrieve courseNameValue
Return courseNameValue
End Get
Set(ByVal value As String) ' set courseNameValue
courseNameValue = value ' store the course name in the object
End Set
End Property ' CourseName
' display a welcome message to the GradeBook user
Public Sub DisplayMessage()
' use property CourseName to display the
' name of the course this GradeBook represents
Console.WriteLine("Welcome to the grade book for " _
& vbCrLf & CourseName & "!")
End Sub ' DisplayMessage
End Class ' GradeBook
Instance variable
courseNameValue
Get accessor for property
courseNameValue
Set accessor for property
courseNameValue
Calls the Get accessor of property
CourseName
7/20/2015
VBN2008-04
19
Helpful Console Hints
7/20/2015
VBN2008-04
20
Predefined Constant
Identifiers
• vbCrLf
– Represents a combination of carriage return
and linefeed character
– Outputting this constant’s value causes
subsequent text to display at the beginning
of the next line
• vbTab
– A constant that represents a Tab character
7/20/2015
VBN2008-04
21
Private keyword
• Used for most instance variables
• Private variables and methods are
accessible only to methods of the class in
which they are declared
• Declaring instance variables Private is
known as information hiding
7/20/2015
VBN2008-04
22
Instance Variables &
Properties continued
• Property Declaration
– Declaration consist of an access modifier, keyword
Property, name with parentheses, and type
– Get and Set allows you to access and modify
private variables outside of the class, respectively
– Contain a Get accessor, Set accessor, or both
– After defining a property, you can use it like a
variable
( object_Name.Property_Name )
7/20/2015
VBN2008-04
23
Instance Variables &
Properties continued
• Get and Set Accessors
– Get accessor contains a Return statement
– Set accessor assigns a value to its
corresponding instance variable
7/20/2015
VBN2008-04
24
Instance Variables &
Properties continued
• Default initial value
– Provided for all fields not initialized
• 0 for numeric/value type variables
• Nothing for Strings and reference types
7/20/2015
VBN2008-04
25
Calls the Get accessor of property
CourseName
' display initial value of property CourseName (invokes Get)
Console.WriteLine( "Initial course name is: " _
& gradeBook.CourseName & vbCrLf)
Calls the Set accessor
of property
‘ prompt for course name
Console.WriteLine("Please enter the course name:") CourseName
‘ read course name
Dim theName As String = Console.ReadLine()
gradeBook.CourseName = theName ' set the CourseName (invokes Set)
Console.WriteLine() ' output a blank line
‘display welcome message including the course name (invokes Get)
gradeBook.DisplayMessage()
End Sub ' Main
Calls the Get accessor of
End Module ' GradeBookTest
property CourseName
7/20/2015
VBN2008-04
26
UML Diagram
– Model properties in the UML as attributes:
•
•
•
•
Public is indicated by the “+” sign
<<Property>>
Property’s name “:” property’s type
If the property only contains a Get accessor, then place
“{ReadOnly}” after the property’s type
– Modeling Private instance variables that
are not properties:
• Attribute’s name “:” attribute’s type
• Private is indicated by the “-” sign
7/20/2015
VBN2008-04
27
UML Class Diagram
Indicates:
• class GradeBook has a courseNameValue
attribute of type String
• one public property and
• one method
7/20/2015
VBN2008-04
28
Instance Variables &
Properties continued
• Public variable
– can be read or written by any property or
method
7/20/2015
VBN2008-04
29
Instance Variables &
Properties continued
• Private variables
– can only be accessed indirectly through the
class’s non-Private properties
– Class able to control how the data is set or
returned
– Allows for data validation
– Properties of a class should use class’s own
methods to manipulate the class’s Private
instance variables
• Creates more robust class
7/20/2015
VBN2008-04
30
Value Types vs. Reference
Types
Types in Visual Basic
7/20/2015
VBN2008-04
31
Types
– Value (primitive types except String)
• Contains a value of that type
• List of Primitive Types in Appendix L
– Reference (sometimes called non-primitive
types)
• Objects
• Default value of Nothing
• Used to invoke an object’s methods and properties
7/20/2015
VBN2008-04
32
Value Type Variable
7/20/2015
VBN2008-04
33
Reference Type Variable
7/20/2015
VBN2008-04
34
Constructors
7/20/2015
VBN2008-04
35
Constructors
– Initialize an object of a class
– Required for every class
– Provides a default no-argument constructor
ONLY when none is provided
– Called when keyword New is followed by
the class name and parentheses
– Can also take arguments
– Header similar to Sub method header
except name is replaced with keyword New
7/20/2015
VBN2008-04
36
Constructor Example
' Fig. 4.12: GradeBook.vb
' GradeBook class with a constructor to initialize the course name.
Public Class GradeBook
Private courseNameValue As String ' course name for this GradeBook
' constructor initializes course name with String supplied as argument
Public Sub New(ByVal name As String)
Constructor to initialize
CourseName = name
' initialize courseNameValue via property
courseNameValue variable
End Sub ' New
Sub Main()
' create GradeBook object
Dim gradeBook1 As New GradeBook( _
"CS101 Introduction to Visual Basic Programming")
Dim gradeBook2 As New GradeBook( _
"CS102 Data Structures in Visual Basic")
Call constructor to create first grade
book object
Create second grade book object
7/20/2015
VBN2008-04
37
UML Class Diagram
– Constructors go in third compartment
– Place “<<constructor>>” before New and its
arguments
– By convention, place constructors first in
their compartment
7/20/2015
VBN2008-04
38
UML class diagram
Indicates that class GradeBook has a constructor
that has a name parameter of type String.
7/20/2015
VBN2008-04
39
Validating Data with Set
Accessors in Properties
• Validations should be made in the Set accessor to
check if the data is valid
• By default, the Get and Set accessor has the same
access as the property, however they can vary.
• String
– Length property returns the number of characters in the
String
– Substring returns a new String object created by copying
part of an existing String object
– To display a double quote, use two double quotes in a row
7/20/2015
VBN2008-04
40
UML Class Diagrams
• Allows suppression of class attributes
and operations
– Called an elided diagram
• Solid line that connects two classes
represents an association
– numbers near end of each line are
multiplicity values
41
7/20/2015
VBN2008-04
Multiplicity Types
7/20/2015
Symbol
Meaning
0
None
1
One
m
An integer value
0..1
Zero or one
m, n
m or n
m..n
At least m, but not more than n
*
Any nonnegative integer (zero or more)
0..*
Zero or more (identical to *)
1..*
One or more
VBN2008-04
42
UML Class Diagrams
• Solid diamonds attached to association
lines indicate a composition relationship
• Hollow diamonds indicate aggregation –
a weaker form of composition
43
7/20/2015
VBN2008-04
Class Diagram showing
Composition Relationships
7/20/2015
VBN2008-04
44
Class Diagram
for the ATM Model
7/20/2015
VBN2008-04
45
Composition Relationships
of a class Car.
Class Diagram
7/20/2015
VBN2008-04
46
ATM System Model
including Class Deposit.
Class Diagram
7/20/2015
VBN2008-04
47
Next?
7/20/2015
VBN2008-04
48