4 objects in visual basic net
play

4. Objects in Visual Basic .NET Creating new data types Overview - PowerPoint PPT Presentation

4. Objects in Visual Basic .NET Creating new data types Overview Creating and destroying objects Encapsulation Methods and Properties Constructors Conditional execution and events Variables value and reference objects


  1. 4. Objects in Visual Basic .NET Creating new data types

  2. Overview � Creating and destroying objects � Encapsulation � Methods and Properties � Constructors � Conditional execution and events � Variables – value and reference objects

  3. Classes � A Class is a template for creating objects � Create one class, get many objects � Class allows definition of composition (what data it will contain) and behaviour (what operations it will support) of an object � Class Objects are different from simple variables (Value Objects) � Need to be explicitly created and assigned to an object variable (using the New keyword) � Can be destroyed (removed from memory) � This distinction makes Class Objects (also known as Reference Objects) slightly more awkward to deal with, but much more efficient

  4. Creating and destroying reference (class) objects BankAccount object created here Sub Main() Dim MyAccount As BankAccount = New BankAccount() MyAccount.Deposit(100.00) MyAccount.Withdraw(20.00) Console.WriteLine(“Balance is £{0}”, MyAccount.GetBalance( )) MyAccount = Nothing End Sub BankAccount object destroyed here (this will also happen automatically if the statement is missed out)

  5. Encapsulation This can be accessed directly by code that uses � Recall that Encapsulation is a the object key feature of object-oriented programming � i.e. Creating capsules of code that provide controlled ways of Public Class BankAccount accessing their internal data Public AccountName As String � Encapsulation can be created Private Balance As Integer End Class using the keywords Private (for restricted access) and This can’t Public (for complete access) as tags on variable, class and member (of class) definitions � Typically, Private is used to deny access to member variables

  6. Class Methods � Methods are operations defined for a class � Usually to alter the value of one or more member variables, or to retrieve some information from them � A method can be a Sub or a Function � A Sub performs some operation on the object � A Function returns a value derived from the data in the object’s member variables � Methods are Public, and so can be accessed by code that uses an object of the class � Allows data in Private member variables to be accessed

  7. A Class � Member variables (AccountName and Public Class BankAccount Balance) store data Public AccountName As String Private Balance As Decimal � Methods (Deposit and Public Sub Deposit(ByVal Amount As Decimal) GetBalance) Balance += Amount manipulate the End Sub member variables or Public Function GetBalance() As Decimal Return Balance retrieve data from them End Function � Public items can be End Class accessed by code outwith the class � Private items can only be accessed by methods of the class

  8. Properties � A Property is a value that is part of an object and made accessible by it � Two ways of creating a property � A Public member variable � A Public Property definition � This is a special type of code routine that provides read and/or write access to values derived from member variables, either public or private ones � Defining a Property for a class gives us a way of restricting access to internal data in whatever way we want

  9. Example Properties Class Circle Public Radius As Single Radius a public Public Property Diameter As Single member variable, and Get behaves as a Property Return 2 * Radius of the class End Get Set(ByVal Value As Single) Radius = Value / 2 Diameter is a Property End Set definition, whose value End Class is determined by program code. Get Sub Main() part determines value Dim C As New Circle when the property is C.Radius = 10 ‘read’, Set part defines Console.WriteLine(C.Diameter) how to update the C.Diameter = 5 property value. Console.WriteLine(C.Radius) End Sub

  10. Using a property to restrict access � A ReadOnly property has only a Get part, so only allows a value to be retrieved from an object � A WriteOnly property has only a Set part, so only allows a value to be assigned (this is more unusual) Class BankAccount ‘ ‘ ‘ ‘ ‘ Public ReadOnly Property CurrentBalance() As Decimal Get Return Balance End Get End Property End Class

  11. Constructors � A new member of a class will initially have all member variables set to zero (0, “”, 0.0, False etc.) � This may be invalid for some objects � e.g. a Circle or radius 0 is not a circle � A Constructor method is a special purpose Sub that is defined to set the initial state of an object when it is created � A Constructor is always called Sub New(), but several versions can be created in which different combinations of data can be used to set the initial state

  12. Example Constructors Public Class BankAccount Public AccountName As String Private Balance As Decimal Public Sub New(ByVal Name As String) AccountName = Name End Sub ‘ ‘ ‘ ‘ ‘ End Class Public Class Circle Public Radius As Single Public Sub New(ByVal InitialRadius As Single) 'This method executes at the point where New is used to 'create a Circle (InitialRadius is the Parameter)... Radius = InitialRadius End Sub ‘ ‘ ‘ ‘ ‘ End Class

  13. Overloaded Constructors � It is possible to define more than one constructor for a class � Versions must differ in number or types of parameters (initial values) passed in Dim MyAccount As BankAccount _ Public Class BankAccount = New BankAccount(“Fred Bloggs”) ‘ ‘ ‘ ‘ ‘ Public Sub New(ByVal Name As String) AccountName = Name End Sub Public Sub New(ByVal Name As String, ByVal Initial As Decimal) AccountName = Name Balance = Initial End Sub Dim MyAccount As BankAccount _ ‘ ‘ ‘ ‘ ‘ = New BankAccount(“Fred Bloggs”, 100) End Class

  14. Conditional execution � It is useful to have certain operations organised so that they will only execute if the conditions are appropriate � Apply discount IF a customer has spent more than £50 � Accept a job applicant IF the person has a programming qualification � This is the key feature that makes computer programs more than simple calculations � A program can behave in a way that adapts to circumstances � In a class, we can use this to make any or all of the methods more ‘intelligent’

  15. Example conditional code Public Class BankAccount ‘ ‘ ‘ ‘ Public Sub Withdraw(ByVal Amount As Decimal) If Amount <= Balance Then Balance -= Amount End If End Sub End Class Withdrawal is only allowed if there is enough cash in the account to cover it.

  16. Events � An event is a signal from an object that something significant has happened � Someone just clicked on a button with the mouse � The last number in a list has been processed � A BankAccount has gone overdrawn � We can define a new type of event to suit whatever circumstances it would be worth responding to � Unlike an If..Then statement that will always respond by executing the code defined within it, an event can be ignored, or a programmer can decide later how to react to it

  17. Example Event Event is defined in 1 the class, and raised Class BankAccount Public Event Overdrawn(ByVal Amount As Decimal) in any section of code that you decide ‘ ‘ ‘ ‘ ‘ should cause it. Public Function Withdraw(ByVal Amount As Decimal) mvarBalance -= Amount If Balance < 0 Then RaiseEvent Overdrawn(mvarBalance) End If Private WithEvents Account As BankAccount End Function 'Other code... End Class Sub DealWithOverdraft(ByVal Amount As Decimal) _ Handles Account.Overdrawn Console.WriteLine("Account is overdrawn by : {0}", Amount) End Sub Sub Main() An event handler is 2 Dim A As BankAccount = New BankAccount defined in a program ‘ ‘ ‘ to indicate how the The event is raised automatically if A.Withdraw(200) event should be 3 the circumstances defined for the End Sub dealt with event occur

  18. Variables � In Visual Basic .NET, every variable is an object, but there are two types: � Value objects (or value types) � Reference objects (or reference types) � A Value object exists as soon as it is declared (with a Dim…, Private… or Public… statement) � It will immediately be given a zero value unless it is initialized � A Reference object must be created with the New keyword – until then, it is Nothing � Until New is used, there is no object and an attempt to access any of its Properties or Methods will cause a crash

  19. Value and Reference objects Sub Main() Dim i As Integer 0 Dim a As BankAccount Nothing BankAccount a = New BankAccount Object ‘ . . . End Sub

  20. Differences between value and reference objects � A value type variable stores the value � A reference type variable is a reference to an object, or Nothing � Copy a value type, create a second copy � Copy a reference type, create a second reference to the same object � After the last statement in a block (e.g. a Sub) is executed, value types declared within it disappear � Objects referred to by reference variables declared within a block can continue to exist provided some reference variable outside the block is made to refer to the object

  21. Distinguishing between value and reference types � The types are simple to recognise � Simple variables are value types � Numbers, dates, characters (char), Booleans, structures, enumerations � All Classes and Strings are reference types � In some cases, strings behave like value types, since they can be copied – this is a deliberate feature

Recommend


More recommend