Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 OOP: Creating Object- Oriented Programs Programming In Visual Basic.NET.

Similar presentations


Presentation on theme: "Chapter 6 OOP: Creating Object- Oriented Programs Programming In Visual Basic.NET."— Presentation transcript:

1 Chapter 6 OOP: Creating Object- Oriented Programs Programming In Visual Basic.NET

2 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Object-Oriented (OO) Program ObjectsObjects –Consist of one or more data values which define the state or properties of the object –Encapsulated by a set of functions (methods) that can be applied to that object DataData Method Method Method Method Message Class

3 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Object-Oriented (OO) Program ClassClass –Defines: Characteristics of the data contained by objects of the classCharacteristics of the data contained by objects of the class Functions that can be applied to the objects of the classFunctions that can be applied to the objects of the class DataData Method Method Method Method DataData Method Method Method Method DataData Method Method Method Method Class

4 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved "Cookie Analogy" Class = Cookie cutterClass = Cookie cutter Instantiate = Making a cookie using the cookie cutterInstantiate = Making a cookie using the cookie cutter Instance = Newly made cookieInstance = Newly made cookie Properties of the Instance may have different valuesProperties of the Instance may have different values –Icing property can be True or False –Flavor property could be Lemon or Chocolate DataData Method Method Method Method DataData Method Method Method Method DataData Method Method Method Method Class Object Object Object

5 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved "Cookie Analogy" (continued) Methods = Eat, Bake, or CrumbleMethods = Eat, Bake, or Crumble Events = Cookie crumbling all by itself and informing youEvents = Cookie crumbling all by itself and informing you Distinction between method and an event is somewhat fuzzy

6 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Object-Oriented Terminology EncapsulationEncapsulation InheritanceInheritance PolymorphismPolymorphism Reusable ClassesReusable Classes Multitier ApplicationsMultitier Applications

7 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Encapsulation Combination of characteristics of an object along with its behavior in "one package"Combination of characteristics of an object along with its behavior in "one package" Cannot make object do anything it does not already "know" how to doCannot make object do anything it does not already "know" how to do Cannot make up new properties, methods, or eventsCannot make up new properties, methods, or events Sometimes referred to as data hiding; an object can expose only those data elements and procedures that it wishesSometimes referred to as data hiding; an object can expose only those data elements and procedures that it wishes

8 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Encapsulation DataData Method Method Method Method Message Class

9 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Inheritance Ability to create a new class from an existing classAbility to create a new class from an existing class – Original class is called Base Class, Superclass, or Parent Class –Inherited class is called Subclass, Derived Class, or Child Class For example, each form created is inherited from the existing Form classFor example, each form created is inherited from the existing Form class Purpose of inheritance is reusabilityPurpose of inheritance is reusability

10 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Inheritance (continued) Examine first line of code for a form in the EditorExamine first line of code for a form in the Editor Public Class Form1 Inherits System.Windows.Forms.Form Inherited Class: Subclass, Derived Class, Child Class Original Class: Base Class, Superclass, Parent Class

11 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Inheritance Example Base ClassBase Class –Person SubclassesSubclasses –Employee –Customer –Student Person -Name -Address -Phone EmployeeStudentCustomer Properties

12 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Polymorphism Methods having identical names but different implementationsMethods having identical names but different implementations OverloadingOverloading –Several argument lists for calling the method –Example: MessageBox.Show method OverridingOverriding –Refers to a class that has the same method name as its base class –Method in subclass takes precedence

13 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Reusability Big advantage of OOP over traditional programmingBig advantage of OOP over traditional programming New classes created can be used in multiple projectsNew classes created can be used in multiple projects Each object created from the class can have its own propertiesEach object created from the class can have its own properties

14 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Multitier Applications Classes are used to create multitier applicationsClasses are used to create multitier applications Each of the functions of a multitier application can be coded in a separate component and stored and run on different machinesEach of the functions of a multitier application can be coded in a separate component and stored and run on different machines Goal is to create components that can be combined and replacedGoal is to create components that can be combined and replaced

15 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Three-tier Model Most popular implementationMost popular implementation Presentation TierBusiness TierData Tier User Interface Forms Controls Menus Business Objects Validation Calculations Business Logic Business Rules Data Retrieval Data Storage

16 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Instantiating An Object Creating a new object based on a classCreating a new object based on a class Create an instance of the class by using the New keywordCreate an instance of the class by using the New keyword General FormGeneral Form New className( )

17 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved New Keyword Examples Dim arialFont As Font = New Font ("Arial", 12) messageLabel.Font = arialFont OR messageLabel.Font = New Font ("Arial", 12)

18 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Specifying a Namespace In your projects, you have noticed the Inherits clause when VB creates a new form classIn your projects, you have noticed the Inherits clause when VB creates a new form class Public Class Form1 Inherits System.Windows.Forms.Form Name of the Class Namespace

19 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Specifying a Namespace (continued) Entire namespace is not needed for any classes in the namespaces that are automatically included in a Windows Forms project which includeEntire namespace is not needed for any classes in the namespaces that are automatically included in a Windows Forms project which include –System –System.Windows.Forms –System.Drawing When referring to a class in a different namespaceWhen referring to a class in a different namespace –Write out the entire namespace or –Add an Imports statement at the top of the code to specify the namespace

20 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Designing Your Own Class Analyze characteristics needed by new objectsAnalyze characteristics needed by new objects –Characteristics or properties are defined as variables –Define the properties as variables in the class module Analyze behaviors needed by new objectsAnalyze behaviors needed by new objects –Behaviors are methods –Define the methods as sub procedures or functions

21 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Creating Properties in a Class Define variables inside the Class module by declaring them as PrivateDefine variables inside the Class module by declaring them as Private Do not make Public, that would violate encapsulation (each object should be in charge of its own data)Do not make Public, that would violate encapsulation (each object should be in charge of its own data)

22 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Property Procedures Properties in a class are accessed with accessor methods in a property procedureProperties in a class are accessed with accessor methods in a property procedure Name used for property procedure is the name of the property seen by the outside worldName used for property procedure is the name of the property seen by the outside world Set StatementSet Statement –Uses Value keyword to refer to incoming value for property –Assigns a value to the property Get StatementGet Statement –Retrieves a property value –Must assign a return value to the procedure name

23 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Property Procedure General Form Private ClassVariable As DataType [Public] Property PropertyName( ) As DataType Get Return ClassVariable [PropertyName = ClassVariable] End Get Set (ByVal Value As DataType) [statements, such As validation] ClassVariable = Value End Set End Property

24 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Read-Only Properties In some instances a value for a property should only be retrieved by an object and not changedIn some instances a value for a property should only be retrieved by an object and not changed –Create a read-only property by using the ReadOnly modifier –Write only the Get portion of the property procedure [Public] ReadOnly Property PropertyName( ) As DataType

25 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Write-Only Properties At times a property can be assigned by an object but not retrievedAt times a property can be assigned by an object but not retrieved –Create a property block that contains only a Set to create a write-only property [Public] WriteOnly Property PropertyName( ) As DataType

26 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Class Methods Create methods by coding public procedures within a classCreate methods by coding public procedures within a class Methods declared with the Private keyword are available only within the classMethods declared with the Private keyword are available only within the class Methods declared with the Public keyword are available to external objectsMethods declared with the Public keyword are available to external objects

27 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Constructors and Destructors ConstructorConstructor –Method that automatically executes when an object is instantiated –Constructor must be public and is named New DestructorDestructor –Method that automatically executes when an object is destroyed

28 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Overloading Methods Overloading means that two methods have the same name but a different list of arguments (the signature)Overloading means that two methods have the same name but a different list of arguments (the signature) Create by giving the same name to multiple procedures in your class module, each with a different argument listCreate by giving the same name to multiple procedures in your class module, each with a different argument list

29 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Parameterized Constructor Constructor that requires argumentsConstructor that requires arguments Allows arguments to be passed when creating an objectAllows arguments to be passed when creating an object

30 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Create a New Class Project, Add ClassProject, Add Class In Add New Item dialog box, choose ClassIn Add New Item dialog box, choose Class Name the ClassName the Class Define the Class propertiesDefine the Class properties To allow access from outside the class, add property proceduresTo allow access from outside the class, add property procedures Code the methodsCode the methods

31 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Creating a New Object Using a Class Similar to creating a new tool for the toolbox but not yet creating an instance of the classSimilar to creating a new tool for the toolbox but not yet creating an instance of the class Declare a variable for the new objectDeclare a variable for the new object Then, instantiate the object using the New keywordThen, instantiate the object using the New keyword Private aBookSale As BookSale aBookSale = New BookSale( ) Or Dim aBookSale As New Booksale( )

32 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Creating a New Object Using a Class (continued) If object variable is needed in multiple procedures, delcare the object at class levelIf object variable is needed in multiple procedures, delcare the object at class level Instantiate the objectInstantiate the object –Only when(if) it is needed –Inside a Try/Catch block for error handling (Try/Catch block must be inside a procedure) Pass values for the arguments at instantiation when using a parameterized constructorPass values for the arguments at instantiation when using a parameterized constructor

33 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Instance Variables versus Shared Variables Instance variables or propertiesInstance variables or properties –Separate memory location for each instance of the object Shared variables or propertiesShared variables or properties –Single variable that is available for ALL objects of a class –Can be accessed without instantiating an object of the class –Use the Shared keyword to create Shared Methods can also be created

34 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Garbage Collection Feature of.NET Common Language Runtime (CLR) that cleans up unused componentsFeature of.NET Common Language Runtime (CLR) that cleans up unused components Periodically checks for unreferenced objects and releases all memory and system resources used by the objectsPeriodically checks for unreferenced objects and releases all memory and system resources used by the objects Microsoft recommends depending on Garbage Collection rather than Finalize proceduresMicrosoft recommends depending on Garbage Collection rather than Finalize procedures

35 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Inheritance New class canNew class can –Be based on another class (base class) –Inherit the properties and methods (but not constructors) of the base class, which can be One of the VB existing classesOne of the VB existing classes Your own classYour own class Use the Inherits statement following the class header and prior to any commentsUse the Inherits statement following the class header and prior to any comments

36 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Overriding Methods Methods with the same name and the same argument list as the base classMethods with the same name and the same argument list as the base class Derived class (subclass) will use the new method rather than the method in the base classDerived class (subclass) will use the new method rather than the method in the base class To override a methodTo override a method –Declare the original method with the Overridable keyword –Declare the new method with the Overrides keyword

37 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Creating a Base Class Strictly for Inheritance Classes can be created strictly for inheritance by two or more similar classes and are never instantiatedClasses can be created strictly for inheritance by two or more similar classes and are never instantiated For a base class that you intend to inherit from, include the MustInherit modifier on the class declarationFor a base class that you intend to inherit from, include the MustInherit modifier on the class declaration In each base class method that must be overridden, include the MustOverride modifier and no code in the base class methodIn each base class method that must be overridden, include the MustOverride modifier and no code in the base class method

38 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Inheriting Form Classes Many projects require several formsMany projects require several forms Create a base form and inherit the visual interface to new formsCreate a base form and inherit the visual interface to new forms Base form inherits from System.Windows.Forms.FormBase form inherits from System.Windows.Forms.Form New form inherits from Base formNew form inherits from Base form

39 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Creating Inherited Form Class Project menu, Add Windows FormProject menu, Add Windows Form Modify the Inherits Statement to inherit from base form using project name as the namespaceModify the Inherits Statement to inherit from base form using project name as the namespace OROR Project menu, Add Inherited FormProject menu, Add Inherited Form In dialog select name of base formIn dialog select name of base form

40 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Coding for Events of an Inherited Class Copy procedure from base class into derived class and make modificationsCopy procedure from base class into derived class and make modifications An alternate way is to use the inherited event handler in the derived classAn alternate way is to use the inherited event handler in the derived class

41 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Managing Multiclass Projects VB projects are automatically assigned a namespace which defaults to the name of the projectVB projects are automatically assigned a namespace which defaults to the name of the project Add an existing class to a project by copying the file into the project folder and then adding the file to the projectAdd an existing class to a project by copying the file into the project folder and then adding the file to the project –Project/Add Existing Item

42 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Displaying Values on a Different Form Refer to controls on another form by using the identifier for the form instanceRefer to controls on another form by using the identifier for the form instance General SyntaxGeneral Syntax ExampleExample FormInstance.ControlName.Property Dim aSummaryForm As New summaryForm( ) aSummaryForm.SalesLabelTotal.Text = aBookSale.SalesTotal.ToString( " C " )

43 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Using the Object Browser Use it to view the names, properties, methods, events and constants of VB objects, your own objects, and objects available from other applicationsUse it to view the names, properties, methods, events and constants of VB objects, your own objects, and objects available from other applications To DisplayTo Display –Click on Tab in Editor Window –Object Browser toolbar button

44 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Object Browser Objects list Browse list Find Symbol Namespace icons Members list Class icon Constants icon Method icon Property icon Description Pane

45 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Examining VB Classes Members of System.Windows.Forms.MessageBox Class

46 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved Examining VB Classes (continued) Display the MessageBoxButtons Constants


Download ppt "Chapter 6 OOP: Creating Object- Oriented Programs Programming In Visual Basic.NET."

Similar presentations


Ads by Google