480 likes | 652 Views
Introduction to Classes & Objects. Chapter 4. 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. Classes. Properties, Methods, & Constructors.
E N D
Introduction to Classes & Objects Chapter 4 VBN2008-04
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 VBN2008-04
Classes Properties, Methods, & Constructors VBN2008-04
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 VBN2008-04
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. System.MathSystem.Windows.Forms.Form VBN2008-04
Object • Is a user interface element • Can be created on VB form using control in Toolbox • Forms are objects • Inherit functionality from their class VBN2008-04
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) VBN2008-04
Methodscont • 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 VBN2008-04
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 End Class ' GradeBook When Method is called, it is output to screen VBN2008-04
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) VBN2008-04
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 VBN2008-04
UML 9 Diagrams VBN2008-04
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 VBN2008-04
Example of UML Diagram • Indicates that class GradeBook has a public DisplayMessage operation. VBN2008-04
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() VBN2008-04
Method with Parameter • Parameters specified in method’s parameter list • Part of method header • Uses a comma-separated list • Keyword ByVal • The argument is passed by value More about ByVal & ByRef later VBN2008-04
UML Example • indicates that classGradeBookhas a DisplayMessageoperation with acourseNameparameter of type String. VBN2008-04
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 VBN2008-04
Getaccessor for property courseNameValue Calls the Getaccessor of propertyCourseName Setaccessor for propertycourseNameValue 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 VBN2008-04
Helpful Console Hints VBN2008-04
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 VBN2008-04
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 VBN2008-04
Instance Variables & Properties continued • Property Declaration • Declaration consist of an access modifier, keyword Property, name with parentheses, and type • GetandSet 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 ) VBN2008-04
Instance Variables & Properties continued • Get and SetAccessors • Get accessor contains a Return statement • Set accessor assigns a value to its corresponding instance variable VBN2008-04
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 VBN2008-04
Calls the Getaccessor of propertyCourseName Calls the Setaccessor of propertyCourseName Calls the Getaccessor of propertyCourseName ' display initial value of property CourseName (invokes Get) Console.WriteLine( "Initial course name is: " _ & gradeBook.CourseName& vbCrLf) ‘ prompt for course name Console.WriteLine("Please enter the course name:") ‘ 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 End Module ' GradeBookTest VBN2008-04
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 VBN2008-04
UML Class Diagram • Indicates: • classGradeBookhas acourseNameValueattribute oftype String • one public property and • one method VBN2008-04
Instance Variables & Properties continued • Public variable • can be read or written by any property or method VBN2008-04
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 VBN2008-04
Value Types vs. Reference Types Types in Visual Basic VBN2008-04
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 VBN2008-04
Value Type Variable VBN2008-04
Reference Type Variable VBN2008-04
Constructors VBN2008-04
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 VBN2008-04
Call constructor to create first grade book object Constructor to initialize courseNameValue variable Create second grade book object 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) CourseName = name ' initialize courseNameValue via property 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") VBN2008-04
UML Class Diagram • Constructors go in third compartment • Place “<<constructor>>” before New and its arguments • By convention, place constructors first in their compartment VBN2008-04
UML class diagram Indicates that classGradeBookhas a constructor that has anameparameter of typeString. VBN2008-04
Validating Data with Set Accessors in Properties • Validations should be made in the Setaccessor to check if the data is valid • By default, the Get and Setaccessor 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 VBN2008-04
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 VBN2008-04
Multiplicity Types VBN2008-04
UML Class Diagrams • Solid diamonds attached to association lines indicate a composition relationship • Hollow diamonds indicate aggregation – a weaker form of composition VBN2008-04
Class Diagram for the ATM Model VBN2008-04
Composition Relationships of a class Car. Class Diagram VBN2008-04
ATM System Model including Class Deposit. Class Diagram VBN2008-04
Next? Control Structures part 1 VBN2008-04