Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 An Introduction to Classes, Objects, and object-oriented development.

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Advertisements

Classes, Exceptions, Collections, and Scrollable Controls
Copyright © 2014 Pearson Education, Inc. Chapter 12 Classes, Collections, and Inheritance.
12-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Road Map Introduction to object oriented programming. Classes
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
VBA Modules, Functions, Variables, and Constants
Chapter 6 OOP: Creating Object-Oriented Programs Programming In Visual Basic.NET.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
ASP.NET Programming with C# and SQL Server First Edition
VB Classes ISYS 512. Adding a Class to a Project Project/Add Class –*** MyClass is a VB keyword. Steps: –Adding properties Declare Public variables in.
CSI 101 Elements of Computing Spring 2009 Lecture # 14 – Classes and Objects Wednesday, April 15th, 2009 and Monday, April 20th, 2009.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
JavaScript, Fourth Edition
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Chapter 6 OOP: Creating Object-Oriented Programs Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Chapter Eleven Classes and Objects Programming with Microsoft Visual Basic th Edition.
CSCI 3327 Visual Basic Chapter 3: Classes and Objects UTPA – Fall 2011.
Chapter 6 OOP: Creating Object-Oriented Programs Programming In Visual Basic.NET.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Microsoft Visual Basic 2008 CHAPTER ELEVEN Multiple Classes and Inheritance.
Programming with Microsoft Visual Basic 2012 Chapter 11: Classes and Objects.
VB Classes ISYS 512/812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Chapter 12 Classes, Collections and Scrollable Controls Topics Classes Abstract Data Types Objects, Properties, Methods Exceptions Collections Object Browser.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Chapter 5 Introduction to Defining Classes
Week Classes Introduction Classes Abstract Data Types Objects, Properties, Methods.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 27 I Love this Class.
Object-Oriented Programming: Inheritance and Polymorphism.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 12 Classes, Collections, and.
Object-Oriented Programming: Classes and Objects.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance and Polymorphism
Introduction to Object-oriented Programming
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Creating Your Own Classes
Programming Logic and Design Seventh Edition
IS 350 Application Structure
Chapter 1: An Introduction to Visual Basic 2015
Object-Oriented Programming: Classes and Objects
Multiple Classes and Inheritance
Microsoft Visual Basic 2005: Reloaded Second Edition
Chapter 3: Using Methods, Classes, and Objects
Road Map Introduction to object oriented programming. Classes
Chapter 4: Writing Classes
Object-Oriented Programming: Classes and Objects
Chapter 11 – Object-Oriented Programming
VISUAL BASIC.
IFS410: Advanced Analysis and Design
Classes, Collections, and Inheritance
Lecture 22 Inheritance Richard Gesick.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Classes and Objects.
Object-Oriented Programming: Classes and Objects
Tonga Institute of Higher Education
Object-Oriented Programming: Inheritance and Polymorphism
CIS16 Application Development and Programming using Visual Basic.net
Presentation transcript:

Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 An Introduction to Classes, Objects, and object-oriented development

Chapter 12, Slide 2Starting Out with Visual Basic 3 rd Edition Chapter 12 Introduction

Chapter 12, Slide 3Starting Out with Visual Basic 3 rd Edition Section 12.1 Classes and Objects Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects

Chapter 12, Slide 4Starting Out with Visual Basic 3 rd Edition Object Oriented Programming  An abstract data type (ADT) is a data type created by a programmer  ADTs are important in computer science and object-oriented programming  An abstraction is 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

Chapter 12, Slide 5Starting Out with Visual Basic 3 rd Edition Object Oriented Programming  A class is a program structure that defines an abstract data type  In application programming it’s usually equivalent to a database table  Think of a class as a pattern or blueprint Defines common characteristics Every “thing” belongs to a class An object is merely an instantiation of a class  Classes have attributes and behaviors Attributes describe properties, like adjectives Behaviors describe actions, like verbs

Chapter 12, Slide 6Starting Out with Visual Basic 3 rd Edition Consider a Person Class  Each person has properties Name, address, hair color, height, weight, age Breed is not a property of this class  Each person can perform methods Run, jump, sit, speak, smile, laugh Bark and wag tail are not methods of this class  The person class is merely a blueprint Defines the characteristics of a person but is not a person Only an instantiation of this class

Chapter 12, Slide 7Starting Out with Visual Basic 3 rd Edition Classes Versus Objects  Must define the class first in your code  Then can create instances of the class  Class instances share common attributes  VB forms and form controls are classes Each control in the toolbox, is its own class Placing a button on a form creates an instance, or object, of the button class

Chapter 12, Slide 8Starting Out with Visual Basic 3 rd Edition Properties, Methods, and 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

Chapter 12, Slide 9Starting Out with Visual Basic 3 rd Edition Object Oriented Design  The challenge is to design classes that effectively cooperate and communicate  Analyze program specifications to determine ADTs that best implement the specifications  Classes are fundamental building blocks Typically represent nouns of some type

Chapter 12, Slide 10Starting Out with Visual Basic 3 rd Edition Object Oriented Design Example Specifications: We need to keep a list of students that lets us track the courses they have completed. Each student has a transcript that 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 course taken by a student.  Nouns from the specification above usually become classes in the program design  Verbs such as calculate GPA and search become methods of those classes

Chapter 12, Slide 11Starting Out with Visual Basic 3 rd Edition OOD Class Characteristics ClassAttributes (properties)Operations (methods) StudentLastName, FirstName, Display, Input IdNumber StudentListAllStudents, CountAdd, Remove, FindStudent CourseName, CreditHrsDisplay, Input TranscriptCourse, Student, GradeDisplay, Search, CalcGradeAvg

Chapter 12, Slide 12Starting Out with Visual Basic 3 rd Edition Interface and Implementation  Class interface is the portion of the class visible to the application programmer  Class implementation is the portion of the class hidden from client programs Private member variables Private properties Private methods  Hiding of all data and procedures inside a class is referred to as encapsulation

Chapter 12, Slide 13Starting Out with Visual Basic 3 rd Edition Section 12.2 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

Chapter 12, Slide 14Starting Out with Visual Basic 3 rd Edition Class Declaration  Examples of MemberDeclarations are presented in the following slides  To create a new class: Clicking 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 Public Class Student MemberDeclarations End Class

Chapter 12, Slide 15Starting Out with Visual Basic 3 rd Edition 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 ‘Student last name Public strFirstName As String ‘Student first name Public strId As String ‘Student ID number End Class

Chapter 12, Slide 16Starting Out with Visual Basic 3 rd Edition Creating an Instance of a Class  A two step process creates a class object  Declare a variable whose type is the class  Create instance of 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 New Student() freshman = New Student() Dim freshman As Student

Chapter 12, Slide 17Starting Out with Visual Basic 3 rd Edition 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 member variables strFirstName, strLastName, and strID Can store values in member variables with freshman.strFirstName = "Joy" freshman.strLastName = "Robinson" freshman.strId = "23G794" object.memberVariable

Chapter 12, Slide 18Starting Out with Visual Basic 3 rd Edition Property Procedure  A property procedure is a function that behaves like 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  Set code often provides data validation logic

Chapter 12, Slide 19Starting Out with Visual Basic 3 rd Edition Property Procedure Syntax Public Property PropertyName() As DataType Get Statements End Get Set(ParameterDeclaration) Statements End Set End Property

Chapter 12, Slide 20Starting Out with Visual Basic 3 rd Edition 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 <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set End Property End Class

Chapter 12, Slide 21Starting Out with Visual Basic 3 rd Edition 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 Set(ByVal value As Single) If value >= 0.0 And value <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set Dim freshman as New Student() freshman.TestAverage = 82.3

Chapter 12, Slide 22Starting Out with Visual Basic 3 rd Edition 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  Use the ReadOnly keyword instead of Public  This causes the propertyName to be read- only -- not settable from outside of the class ReadOnly Property PropertyName() As DataType Get Statements End Get End Property

Chapter 12, Slide 23Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 24Starting Out with Visual Basic 3 rd Edition 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  Variable is a candidate for garbage collection when it no longer references an object  The garbage collector runs periodically destroying objects no longer needed freshman = Nothing

Chapter 12, Slide 25Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 26Starting Out with Visual Basic 3 rd Edition 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.)

Chapter 12, Slide 27Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 28Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 29Starting Out with Visual Basic 3 rd Edition  Can create an entire array of object variables Declare an array whose type is a class Instantiate an object for each element Creating an Array of Objects ' Declare the array Dim mathStudents(9) As Student Dim i As Integer For i = 0 To 9 ' Assign each element to an object mathStudents(i) = New Student() Next i

Chapter 12, Slide 30Starting Out with Visual Basic 3 rd Edition  Can use object variables as arguments to a sub or function Example: student object s as an argument  Pass object variable with the procedure call Objects As Procedure Arguments 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)

Chapter 12, Slide 31Starting Out with Visual Basic 3 rd Edition Functions Can Return Objects Dim freshman As Student = GetStudent() … Function GetStudent() As Student Dim s As New Student() s.FirstName = InputBox("Enter the first name.") s.LastName = InputBox("Enter the last name.") s.IdNumber = InputBox("Enter the ID number.") s.TestAverage = InputBox("Enter the test average.") Return s End Function  Example below instantiates a student object  Prompts for and sets its property values  Then returns the instantiated object

Chapter 12, Slide 32Starting Out with Visual Basic 3 rd Edition Class Methods  In addition to properties, a class may also contain sub and function procedures  Methods are procedures 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

Chapter 12, Slide 33Starting Out with Visual Basic 3 rd Edition 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 sngTestAverage As Single 'Holds test avg (...Property procedures omitted...) ' Clear method Public Sub Clear() strFirstName = String.Empty strLastName = String.Empty strId = String.Empty sngTestAverage = 0.0 End Sub End Class

Chapter 12, Slide 34Starting Out with Visual Basic 3 rd Edition Constructors  A constructor is 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

Chapter 12, Slide 35Starting Out with Visual Basic 3 rd Edition 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 sngTestAverage As Single 'Holds test avg ' Constructor Public Sub New() strFirstName = "(unknown)" strLastName = "(unknown)" strId = "(unknown)" testAvg = 0.0 End Sub (The rest of this class is omitted.) End Class

Chapter 12, Slide 36Starting Out with Visual Basic 3 rd Edition Create a Class  Set up a Student class txtLastName txtFirstName txtIdNumber txtTestAverage lblGrade btnExit btnSave

Chapter 12, Slide 37Starting Out with Visual Basic 3 rd Edition Section 12.7 Introduction to Inheritance Inheritance Allows a New Class to be Based on an Existing Class The New Class Inherits the Accessible Member Variables, Methods, and Properties of the Class on Which It Is Based

Chapter 12, Slide 38Starting Out with Visual Basic 3 rd Edition Why Inheritance?  Inheritance allows 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

Chapter 12, Slide 39Starting Out with Visual Basic 3 rd Edition Base and Derived Classes  The Base Class is a 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

Chapter 12, Slide 40Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 41Starting Out with Visual Basic 3 rd Edition The Truck Class (Derived 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 Public Class Truck Inherits Vehicle ' Other new properties ' Additional methods End Class

Chapter 12, Slide 42Starting Out with Visual Basic 3 rd Edition Instantiating the Truck Class  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 Dim pickUp as New Truck() pickUp.Passengers = 2 pickUp.MilesPerGallon = 18 pickUp.MaxCargoWeight = 2000 Pickup.FourWheelDrive = True

Chapter 12, Slide 43Starting Out with Visual Basic 3 rd Edition Overriding Properties and Methods  Sometimes a base class property procedure or method does not work 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

Chapter 12, Slide 44Starting Out with Visual Basic 3 rd Edition 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

Chapter 12, Slide 45Starting Out with Visual Basic 3 rd Edition Overridable Base Class Property Public Overridable Property Passengers() As Integer Get Return intPassengers End Get Set(ByVal value As Integer) intPassengers = value End Set End Property  Overridable keyword added to base class property procedure

Chapter 12, Slide 46Starting Out with Visual Basic 3 rd Edition Overridden Derived Class Property 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  Overrides keyword and new logic added to derived class property procedure

Chapter 12, Slide 47Starting Out with Visual Basic 3 rd Edition Overriding Methods Public Overridable Sub ProcedureName() Public Overridable Function ProcedureName() As DataType Public Overrides Sub ProcedureName() Public Overrides Function ProcedureName() As DataType  Overriding a method is similar to a property  Specify Overridable and Overrides keywords  An overridable base class method  An overriding derived class method

Chapter 12, Slide 48Starting Out with Visual Basic 3 rd Edition Overriding the ToString Method  Every programmer created class is derived from a built-in class named Object  Object class has a method named ToString which returns a fully-qualified class name  Method can be overridden to return a string representation of data stored in an object

Chapter 12, Slide 49Starting Out with Visual Basic 3 rd Edition ToString Override Example ' Overriden ToString method Public Overrides Function ToString() As String ' Return a string representation ' of a vehicle. Dim str As String str = "Passengers: " & numPassengers.ToString & _ " MPG: " & mpg.ToString Return str End Function  Object class ToString method is Overridable  Vehicle class might override the ToString method as shown below

Chapter 12, Slide 50Starting Out with Visual Basic 3 rd Edition Base & Derived Class Constructors  A constructor (named New) may be defined for both the base class and a derived class  When a new object of the derived class is created, both constructors are executed The constructor of the base class will be called first Then the constructor of the derived class will be called

Chapter 12, Slide 51Starting Out with Visual Basic 3 rd Edition Protected Members  In addition to Private and Public, the access specifier may be Protected Protected base class members are treated as public to classes derived from this base Protected base class members are treated as private to classes not derived from this base