1 / 42

Week

Week. 11. Classes. Introduction. Classes Abstract Data Types Objects, Properties, Methods. Classes and Objects. Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects. Abstract Data Types.

addison
Download Presentation

Week

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 11 Classes

  2. Introduction • Classes • Abstract Data Types • Objects, Properties, Methods

  3. Classes and Objects Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects

  4. Abstract Data Types • An abstract data type (ADT) is a data type created by a programmer • ADTs are important in computer science and object-oriented programming • An abstractionis a model of something that includes only its general characteristics • Dog is an abstraction • Defines a general type of animal but not a specific breed, color, or size • A dog is like a data type • A specific dog is an instance of the data type

  5. Classes • A classis a program structure that defines an abstract data type • Must create the class first • Then can create instances of the class • Class instances share common attributes • VB forms and controls are classes • Each control in the toolbox represents a class • Placing a buttonon a form creates an instance, or object, of the class

  6. Class Properties, Methods, & Events • Programs communicate with an object using the properties and methods of the class • Class properties example: Buttons have Location, Text, and Name properties • Class methods example: The Focus method functions identically for every single button • Class event procedures: Each button in a form has a different click event procedure

  7. Object Oriented Design • The challenge is to design classes that effectively cooperate and communicate • Analyze application requirements to determine ADTs that best implement the specifications • Classes are fundamental building blocks • Typically represent nouns of some type • A well-designed class may outlive the application • Other uses for the class may be found

  8. Object Oriented Design Example Specifications: We need to keep a list of studentsthat lets us track the courses they have completed. Each student has a transcriptthat contains all information about his or her completed courses. At the end of each semester, we will calculate the grade point average of each student. At times, users will search for a particular coursetaken by a student. • Nouns from the specification above typically become classes in the program design • Verbs such as calculate GPA and search become methods of those classes

  9. OOD Class Characteristics ClassAttributes (properties)Operations (methods) Student LastName, FirstName, Display, Input IdNumber StudentList AllStudents, Count Add, Remove, FindStudent Course Semester, Name, Display, Input Grade,Credits Transcript CourseList, Count Display, Search, CalcGradeAvg

  10. Interface and Implementation • Class interfaceis the portion of the class visible to the application programmer • Made available by creating properties, methods, and events that are public • Class implementationis the portion of the class hidden from client programs • Kept hidden by designating member variables, properties, & methods as private • Hiding of data and procedures inside a class is referred to as encapsulation

  11. Creating a Class To Create a Class in Visual Basic, You Create a Class Declaration The Class Declaration Specifies the Member Variables, Properties, Methods, and Events That Belong to the Class

  12. Class Declaration Public Class Student MemberDeclarations End Class • Student is the name of the class • Examples of MemberDeclarationsare presented in the following slides • To create a new class: • Click Add New Item button on toolbar • Select Class from Add New Item dialog box • Provide a name for the class and click Add • Adds a new, empty class file (.vb) to project

  13. Member Variables • A variable declared inside a class declaration • Syntax: • AccessSpecifier may be Public or Private • Example: AccessSpecifer VariableName As DataType Public Class Student Public strLastName As String ‘Holds last name Public strFirstName As String ‘Holds first name Public strId As String ‘Holds ID number End Class

  14. Creating an Instance of a Class • A two step process creates an instance of a class • Declare a variable whose type is the class • Create instance of the class with New keyword and assign the instance to the variable • freshman defined here as an object variable • Can accomplish both steps in one statement Dim freshman As Student freshman = New Student Dim freshman As New Student

  15. Accessing Members • Can work with Public member variables of a class object in code using this syntax: • For example: • If freshman references a Student class object • And Student class has public member variables strFirstName, strLastName, and strID • Can store values in member variables with objectVariable.memberVariable freshman.strFirstName = "Joy" freshman.strLastName = "Robinson" freshman.strId = "23G794"

  16. Property Procedure • A property procedure is a function that defines a property • Controls access to property values • Procedure has two sections: Get and Set • Get code executes when value is retrieved • Set code executes when value is stored • Properties almost always declared Public to allow access from outside the class

  17. Property Procedure Syntax Public Property PropertyName() As DataType Get Statements End Get Set(ParameterDeclaration) Statements End Set End Property

  18. Property Procedure Example Public Class Student ' Member variables Private sngTestAvg As Single Public Property TestAverage() As Single Get Return sngTestAvg End Get Set(ByVal value As Single) If value >= 0.0 And value <= 100.0 Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set End Property End Class

  19. Setting and Validating a Property • TestAverage property is set as shown: • Passes 82.3 into value parameter of Set • If in the range 0.0 to 100.0, value is stored • If outside the range, message box displayed instead of value being stored Dim freshman as New Student() freshman.TestAverage = 82.3 Set(ByVal value As Single) If value >= 0.0 And value <= 100.0 Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set

  20. Read-Only Properties • Useful at times to make a property read-only • Allows access to property values but cannot change these values from outside the class • Add ReadOnly keyword after access specifier • This causes the propertyName to be read-only -- not settable from outside of the class Public ReadOnly Property PropertyName() As DataType Get Statements End Get End Property

  21. Read-Only Property Example • ' TestGrade property procedure • ReadOnly Property TestGrade() As Char • Get • If sngTestAverage >= 90 • return "A“ • Else If sngTestAverage >= 80 • return "B“ • Else If sngTestAverage >= 70 • return "C“ • Else If sngTestAverage >= 60 • return "D“ • Else • return "F“ • End If • End Get • End Property

  22. Object Removal & Garbage Collection • Memory space is consumed when objects are instantiated • Objects no longer needed should be removed • Set object variable to Nothing so it no longer references the object • Object is a candidate for garbage collection when it is no longer referenced by any object variable • The garbage collector monitors for and automatically destroys objects no longer needed freshman = Nothing

  23. Going Out of Scope • An object variable instantiated within a procedure is local to that procedure • An object goes out of scope when • Referenced only by local variables and • The procedure ends • Object removed once it goes out of scope • An object instantiated in a procedure and assigned to a global variable is not removed • Reference remains when procedure ends

  24. Going Out of Scope, Example Sub CreateStudent() Dim sophomore As Student sophomore = New Student() sophomore.FirstName = "Travis" sophomore.LastName = "Barnes" sophomore.IdNumber = "17H495" sophomore.TestAverage = 94.7 g_studentVar = sophomore End Sub With this statement, sophomore will not go out of scope. Without this statement, it will go out of scope when the procedure ends. (g_studentVar is a module-level variable.)

  25. Comparing Object Variables • Multiple variables can reference the same object • Can test if two variables refer to same object • Must use the Is operator • The = operator cannot be used to test for this Dim collegeStudent As Student Dim transferStudent As Student collegeStudent = New Student() transferStudent = collegeStudent If collegeStudent Is transferStudent Then ' Perform some action End If

  26. IsNot & Nothing Object Comparisons • Use the IsNot operator to determine that two variables do not reference the same object • Use the special value Nothing to determine if a variable has no object reference If collegeStudent IsNot transferStudent Then ' Perform some action End If If collegeStudent Is Nothing Then ' Perform some action End If

  27. Objects As Procedure Arguments • Can use object variables as arguments to a procedure or function • Example: student object s as an argument • Pass object variable with the procedure call Sub DisplayStudentGrade(ByVal s As Student) ' Displays a student’s grade. MessageBox.Show("The grade for " & _ s.FirstName & " " & s.LastName & _ " is " & s.TestGrade.ToString) End Sub DisplayStudentGrade(freshman)

  28. Functions Can Return Objects • Example below instantiates a student object • Prompts for and sets its property values • Then returns the instantiated object Dim freshman As Student = GetStudent() … Function GetStudent() As Student Dim s As New Student() s.FirstName = InputBox("Enter first name.") s.LastName = InputBox("Enter last name.") s.IdNumber = InputBox("Enter ID number.") s.TestAvg = CSng(InputBox("Enter test average.")) Return s End Function

  29. Class Methods • In addition to properties, a class may also contain Sub procedures and functions • Methods are Sub procedures and functions defined in a class • Typically operate on data stored in the class • The following slide shows a Clear method for the Student class • Method called with freshman.Clear() • Method clears member data in the Student class object referenced by freshman

  30. Clear Method for Student Class Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg (...Property procedures omitted...) ' Clear method Public Sub Clear() strFirstName = String.Empty strLastName = String.Empty strId = String.Empty sngTestAvg = 0.0 End Sub End Class

  31. Constructors • A constructoris a method called automatically when an instance of the class is created • Think of constructors as initialization routines • Useful for initializing member variables or performing other startup operations • To create a constructor, simply create a Sub procedure named New within the class • Next slide shows a Student class constructor • The statement freshman = New Student() • Creates an instance of the Student class • Executes constructor to initialize properties of the Student object referenced by freshman

  32. Constructor Example Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg ' Constructor Public Sub New() strFirstName = "(unknown)" strLastName = "(unknown)" strId = "(unknown)" sngTestAvg = 0.0 End Sub (The rest of this class is omitted.) End Class

  33. Why Inheritance? • Inheritanceallows new classes to derive their characteristics from existing classes • The Student class may have several types of students such as • GraduateStudent • ExchangeStudent • StudentEmployee • These can become new classes and share all the characteristics of the Student class • Each new class would then add specialized characteristics that differentiate them

  34. Base and Derived Classes • The Base Class is a general-purpose class that other classes may be based on • A Derived Class is based on the base class and inherits characteristics from it • Can think of the base class as a parent and the derived class as a child

  35. The Vehicle Class (Base Class) • Consider a Vehicle class with the following: • Private variable for number of passengers • Private variable for miles per gallon • Public property for number of passengers(Passengers) • Public property for miles per gallon(MilesPerGallon) • This class holds general data about a vehicle • Can create more specialized classes from the Vehicle class

  36. The Truck Class (Derived Class) Public Class Truck Inherits Vehicle ' Other new properties ' Additional methods End Class • Declared as: • Truck class derived from Vehicle class • Inherits all non-private methods, properties, and variables of Vehicle class • Truck class defines two properties of its own • MaxCargoWeight – holds top cargo weight • FourWheelDrive – indicates if truck is 4WD

  37. Instantiating the Truck Class Dim pickUp as New Truck() pickUp.Passengers = 2 pickUp.MilesPerGallon = 18 pickUp.MaxCargoWeight = 2000 Pickup.FourWheelDrive = True • Instantiated as: • Values stored in MaxCargoWeight and FourWheelDrive properties • Properties declared explicitly by Truck class • Values also stored in MilesPerGallon and Passengers properties • Properties inherited from Vehicle class

  38. Overriding Properties and Methods • Sometimes a base class property procedure or method must work differently for a derived class • Can override base class method or property • Must write the method or property as desired in the derived class using same name • When an object of the derived class accesses the property or calls the method • VB uses overridden version in derived class • Version in base class is not used

  39. Property Override Example • Vehicle class has no restriction on number of passengers • But may wish to restrict the Truck class to two passengers at most • Can override Vehicle class Passengers property by: • Coding Passengers property in derived class • Specify Overridable in base class property • Specify Overrides in derived class property

  40. Overridable Base Class Property • Overridable keyword added to base class property procedure Public Overridable Property Passengers() As Integer Get Return intPassengers End Get Set(ByVal value As Integer) intPassengers = value End Set End Property

  41. Overridden Derived Class Property • Overrides keyword and new logic added to derived class property procedure Public Overrides Property Passengers() As Integer Get Return MyBase.Passengers End Get Set(ByVal value As Integer) If value >= 1 And value <= 2 Then MyBase.Passengers = value Else MessageBox.Show("Passengers must be 1 or 2", _ "Error") End If End Set End Property

  42. Overriding Methods • Overriding a method is similar to a property • Specify Overridable and Overrides keywords • An overridable base class method • An overriding derived class method Public Overridable Sub ProcedureName() Public Overridable Function ProcedureName() As DataType Public Overrides Sub ProcedureName() Public Overrides Function ProcedureName() As DataType

More Related