Transcript
  • Chapter 6OOP: Creating Object-Oriented ProgramsProgramming InVisual Basic .NET

  • Object-Oriented (OO) ProgramObjectsConsist of one or more data values which define the state or properties of the objectEncapsulated by a set of functions (methods) that can be applied to that objectDataMethodMethodMethodMethodMessageClass

  • Object-Oriented (OO) ProgramClassDefines:Characteristics of the data contained by objects of the classFunctions that can be applied to the objects of the classDataMethodMethodMethodMethodDataMethodMethodMethodMethodDataMethodMethodMethodMethodClass

  • "Cookie Analogy"Class = Cookie cutterInstantiate = Making a cookie using the cookie cutterInstance = Newly made cookieProperties of the Instance may have different valuesIcing property can be True or FalseFlavor property could be Lemon or ChocolateDataMethodMethodMethodMethodDataMethodMethodMethodMethodDataMethodMethodMethodMethodClassObjectObjectObject

  • "Cookie Analogy" (continued)Methods = Eat, Bake, or CrumbleEvents = Cookie crumbling all by itself and informing youDistinction between method and an event is somewhat fuzzy

  • Object-Oriented Terminology Encapsulation InheritancePolymorphismReusable ClassesMultitier Applications

  • EncapsulationCombination 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 up new properties, methods, or eventsSometimes referred to as data hiding; an object can expose only those data elements and procedures that it wishes

  • EncapsulationDataMethodMethodMethodMethodMessageClass

  • InheritanceAbility to create a new class from an existing class Original class is called Base Class, Superclass, or Parent ClassInherited class is called Subclass, Derived Class, or Child ClassFor example, each form created is inherited from the existing Form classPurpose of inheritance is reusability

  • Inheritance (continued)Examine first line of code for a form in the EditorPublic Class Form1Inherits System.Windows.Forms.FormInherited Class: Subclass, Derived Class, Child ClassOriginal Class: Base Class, Superclass, Parent Class

  • Inheritance ExampleBase ClassPersonSubclassesEmployeeCustomerStudentProperties

  • PolymorphismMethods having identical names but different implementationsOverloadingSeveral argument lists for calling the methodExample: MessageBox.Show methodOverridingRefers to a class that has the same method name as its base classMethod in subclass takes precedence

  • ReusabilityBig advantage of OOP over traditional programmingNew classes created can be used in multiple projectsEach object created from the class can have its own properties

  • Multitier ApplicationsClasses are used to create multitier applicationsEach of the functions of a multitier application can be coded in a separate component and stored and run on different machinesGoal is to create components that can be combined and replaced

  • Three-tier ModelMost popular implementation

  • Instantiating An ObjectCreating a new object based on a classCreate an instance of the class by using the New keywordGeneral FormNew className( )

  • New Keyword ExamplesDim arialFont As Font = New Font ("Arial", 12)messageLabel.Font = arialFontORmessageLabel.Font = New Font ("Arial", 12)

  • Specifying a NamespaceIn your projects, you have noticed the Inherits clause when VB creates a new form classPublic Class Form1Inherits System.Windows.Forms.FormName of the ClassNamespace

  • 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 includeSystemSystem.Windows.FormsSystem.DrawingWhen referring to a class in a different namespaceWrite out the entire namespace orAdd an Imports statement at the top of the code to specify the namespace

  • Designing Your Own ClassAnalyze characteristics needed by new objectsCharacteristics or properties are defined as variablesDefine the properties as variables in the class moduleAnalyze behaviors needed by new objectsBehaviors are methodsDefine the methods as sub procedures or functions

  • Creating Properties in a ClassDefine variables inside the Class module by declaring them as PrivateDo not make Public, that would violate encapsulation (each object should be in charge of its own data)

  • Property ProceduresProperties in a class are accessed with accessor methods in a property procedureName used for property procedure is the name of the property seen by the outside worldSet StatementUses Value keyword to refer to incoming value for propertyAssigns a value to the propertyGet StatementRetrieves a property valueMust assign a return value to the procedure name

  • Property Procedure General FormPrivate ClassVariable As DataType[Public] Property PropertyName( ) As DataTypeGetReturn ClassVariable [PropertyName = ClassVariable]End Get

    Set (ByVal Value As DataType)[statements, such As validation]ClassVariable = ValueEnd SetEnd Property

  • Read-Only PropertiesIn some instances a value for a property should only be retrieved by an object and not changedCreate a read-only property by using the ReadOnly modifierWrite only the Get portion of the property procedure[Public] ReadOnly Property PropertyName( ) As DataType

  • Write-Only PropertiesAt times a property can be assigned by an object but not retrievedCreate a property block that contains only a Set to create a write-only property[Public] WriteOnly Property PropertyName( ) As DataType

  • Class MethodsCreate methods by coding public procedures within a classMethods declared with the Private keyword are available only within the classMethods declared with the Public keyword are available to external objects

  • Constructors and DestructorsConstructorMethod that automatically executes when an object is instantiatedConstructor must be public and is named NewDestructorMethod that automatically executes when an object is destroyed

  • Overloading MethodsOverloading 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 list

  • Parameterized ConstructorConstructor that requires argumentsAllows arguments to be passed when creating an object

  • Create a New ClassProject, Add ClassIn Add New Item dialog box, choose ClassName the ClassDefine the Class propertiesTo allow access from outside the class, add property proceduresCode the methods

  • Creating a New Object Using a ClassSimilar to creating a new tool for the toolbox but not yet creating an instance of the classDeclare a variable for the new objectThen, instantiate the object using the New keywordPrivate aBookSale As BookSaleaBookSale = New BookSale( )OrDim aBookSale As New Booksale( )

  • Creating a New Object Using a Class (continued)If object variable is needed in multiple procedures, delcare the object at class levelInstantiate the objectOnly when(if) it is neededInside 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 constructor

  • Instance Variables versus Shared VariablesInstance variables or propertiesSeparate memory location for each instance of the objectShared variables or propertiesSingle variable that is available for ALL objects of a classCan be accessed without instantiating an object of the classUse the Shared keyword to createShared Methods can also be created

  • Garbage CollectionFeature of .NET Common Language Runtime (CLR) that cleans up unused componentsPeriodically checks for unreferenced objects and releases all memory and system resources used by the objectsMicrosoft recommends depending on Garbage Collection rather than Finalize procedures

  • InheritanceNew class canBe based on another class (base class)Inherit the properties and methods (but not constructors) of the base class, which can beOne of the VB existing classesYour own classUse the Inherits statement following the class header and prior to any comments

  • Overriding MethodsMethods with the same name and the same argument list as the base classDerived class (subclass) will use the new method rather than the method in the base classTo override a methodDeclare the original method with the Overridable keyword Declare the new method with the Overrides keyword

  • Creating a Base Class Strictly for InheritanceClasses can be created strictly for inheritance by two or more similar classes and are never instantiatedFor a base class that you intend to inherit from, include the MustInherit modifier on the class declarationIn each base class method that must be overridden, include the MustOverride modifier and no code in the base class method

  • Inheriting Form ClassesMany projects require several formsCreate a base form and inherit the visual interface to new formsBase form inherits from System.Windows.Forms.FormNew form inherits from Base form

  • Creating Inherited Form ClassProject menu, Add Windows FormModify the Inherits Statement to inherit from base form using project name as the namespaceORProject menu, Add Inherited FormIn dialog select name of base form

  • Coding for Events of an Inherited ClassCopy procedure from base class into derived class and make modificationsAn alternate way is to use the inherited event handler in the derived class

  • Managing Multiclass ProjectsVB projects are automatically assigned a namespace which defaults to the name of the projectAdd an existing class to a project by copying the file into the project folder and then adding the file to the projectProject/Add Existing Item

  • Displaying Values on a Different FormRefer to controls on another form by using the identifier for the form instanceGeneral SyntaxExampleFormInstance.ControlName.PropertyDim aSummaryForm As New summaryForm( )aSummaryForm.SalesLabelTotal.Text = aBookSale.SalesTotal.ToString("C")

  • Using the Object BrowserUse it to view the names, properties, methods, events and constants of VB objects, your own objects, and objects available from other applicationsTo DisplayClick on Tab in Editor WindowObject Browser toolbar button

  • Object BrowserObjectslistBrowselistFindSymbolNamespaceiconsMemberslistClassiconConstantsiconMethod iconProperty iconDescription Pane

  • Examining VB ClassesMembers ofSystem.Windows.Forms.MessageBox Class

  • Examining VB Classes (continued)Display theMessageBoxButtons Constants


Top Related