Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

Similar presentations


Presentation on theme: "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."— Presentation transcript:

1 Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

2

3  Class (object type) — A template or blue-print for an object ◦ A class specifies the general format of an object. ◦ It has methods and properties from which similar objects can be created.  Object — An instance or copy of a class for which data are stored and manipulated.  Properties— A set of attribute values available for an object.  Method — A process that performs an action on an object.  Encapsulation — Hiding implementation details by bundling an object’s data and its methods so that the only way to access the data is through the object’s own methods.  Event — An occurrence that generates a signal.  Client – Other objects that get services from another object – the calling program code  Inheritance — The principle that allows an object to get attributes and  methods from its superclass.  Operation — An external view of an object that can be accessed by  other objects.  Polymorphism — The property of an operation or method that allows  it to produce similar results in different objects or at different levels.  Signal — A message that allows objects to interact with other objects. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

4  Visual Objects: ◦ Objects that have visual components (GUI) such as forms, buttons, labels, etc. ◦ These objects have build-in methods and properties that can be set at design time or run-time. ◦ All other qualities of objects (encapsulation, inheritance, Polymorphism, etc.) are hidden by the developement framework  User-Defined Objects: No visual component ◦ Objects created during run-time ◦ Only created through program codes ◦ Equivalent to code view of Visual objects ◦ All other qualities of objects (inheritance, Polymorphism, etc.) are provided by the programmer © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

5  Performing a task in a program requires a method.  The method describes the mechanisms that actually perform its tasks.  The method hides these mechanisms from its user  In a class, you provide one or more methods that are designed to perform the class’s tasks. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

6  To interact with an object, you send messages to an object—each message is a method call that tells one of the object’s methods to perform its task.  Any program code that interacts with any objects of a particular class (from outside those objects) is known as a client of that class—objects provide services to the class’s clients. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

7  A car object can have many attributes, such as its color, the number of doors, the amount of gas in its tank, its current speed and its odometer reading.  Similarly, an object has attributes that are carried with it as it’s used in a program.  These attributes are specified in the object’s class.  Attributes are specified by a class’s instance variables. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

8  We begin with a business example that consists of classes Account and AccountTest.  The Account class (declared in file Account.vb of Fig. 9.2) represents a bank account that has a balance.  Client: The AccountTest class (Fig. 9.3) creates and uses an object of class Account.  The classes are placed in separate files for clarity, but it’s possible to place them in the same file. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

9  When the program initially executes, it creates an Account object and displays its initial balance in the  The user can enter a deposit or withdrawal amount in the inputTextBox, then press the Deposit Button to make a deposit or the Withdraw Button to make a withdrawal.  After each operation, the balance is updated with the new balance. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

10

11  Adding a Class to a Project: ◦ To do this, right click the project name in the Solution Explorer and select Add > Class… from the menu that appears. ◦ In the Add New Item dialog that appears, enter the name of your new file—in this case Account.vb —then click the Add Button. ◦ A new file will be added to your project with an empty Account class. ◦ Add the code from Fig. 9.2 to this file. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

12  Account Class Declaration ◦ The Account class declaration (Fig. 9.2) begins at line 3. ◦ The keyword Public is an access modifier. ◦ Only Public classes can be reused in other projects. ◦ Every class declaration contains keyword Class followed immediately by the class’s name. ◦ Every class’s body ends with the keywords End Class, as in line 49. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

13 Defining the Class Constructor Instance Variable

14 © 1992-2011 by Pearson Education, Inc. All Rights Reserved. Methods

15 © 1992-2011 by Pearson Education, Inc. All Rights Reserved. End of Class Property

16  Class Account contains one instance variable— balanceValue (line 4)—that Account ’s balance.  Before we declared instance variables with the keyword Dim.  Here, we use the Private member-access modifier.  Class members declared with member access modifier Private are accessible only within the class, which gives the class complete control over how those members are used.  This is known as encapsulating the data in the class. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

17  Class members declared with member-access modifier Public are accessible wherever the program has a reference to an Account object.  Instance variables declared with Dim default to Private access.  For clarity, every instance variable and method definition should be preceded by a member access modifier.  We’ll explicitly use Private rather than Dim to indicate that our instance variables are Private. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

18  When you create an object of a class, the class’s constructor is called to initialize the object.  A constructor call is required for every object that’s created.  The compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.  Alternatively, you can provide a parameterless constructor that contains code and takes no parameters, or that takes only Optional parameters so you can call it with no arguments. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

19  If you provide any constructors for a class, the compiler will not provide a default constructor for that class.  Constructors must be named New and are generally declared Public — Private constructors are beyond the scope of the book.  Constructors are implemented as Sub procedures, because they cannot return values. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

20  Method Deposit ◦ Method Deposit (lines 18–26) receives a deposit amount as an argument and attempts to add that amount to the balance. ◦ If depositAmount is less than or equal to 0, it throw an Argu-ment-OutOfRangeException.  Method Withdraw ◦ Method Withdraw (lines 29–41) receives a withdrawal amount as an argument and attempts to subtract that amount from the balance. ◦ If the withdrawalAmount is not valid, it throws an ArgumentOutOfRangeException. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

21  Property Balance ◦ A class’s methods can manipulate the class’s Private instance variables, but clients cannot. ◦ Classes often provide Public properties that allow clients to assign values to (set) or obtain the values of (get) Private instance variables. ◦ Each property contains a Set accessor (to modify the variable’s value) and/or a Get accessor (to retrieve the variable’s value). ◦ For the Account class, we’d like the client code to be able to get the Account ’s balance, but not modify it—all modifications should be performed by methods Deposit and Withdraw. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

22  Property Balance ◦ A property is defined with the Property … End Property keywords. ◦ A property that can be used only to get a value is declared as a ReadOnly property and provides only a Get accessor. ◦ Lines 44–48 define class Account ’s Public ReadOnly property named Balance. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

23  Property Balance ◦ We also use the property inside the method Withdraw when we check whether the withdrawal-Amount is greater than the current balance. ◦ When the compiler sees Balance used in a way that needs a value, it invokes the property’s Get accessor (lines 45– 47). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

24  Class AccountTest ◦ The AccountTest class declaration (Fig. 9.3) creates an object or an instance of Account class declared before. ◦ The variable’s type is Account —the class we declared in Fig. 9.2. ◦ Each new class you create becomes a new type that can be used to declare variables and create objects. ◦ You can declare new class types as needed; this is one reason why Visual Basic is known as an extensible language. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

25 Class AccountTest: The Client The AccountTest class declaration below creates an object or an instance of Account class declared before. Properties and methods of Account Class are available to new object Account

26 © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

27

28

29

30  New creates a new object of the class specified to the right of the New keyword (that is, Account ).  The class name is followed by parentheses, which together with the class name represent a call to class’s constructor.  Because we didn’t pass an argument, the default value 0D is used for the Account ’s initial balance  When there are no arguments, the parentheses can be omitted, though we include them for clarity.  Although Visual Basic is not case sensitive, it does allow you to create objects (for example, account ) with the “same” name as their class (e.g. Account ) © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

31  We now discuss a Time class with three Integer instance variables— hourValue, minuteValue and secondValue —representing the time in universal- time (24-hour clock) format. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

32  GUI for Testing Class Time ’s Properties ◦ The GUI for this application is shown in Fig. 9.10. ◦ You can set the hour, minute and second using the three TextBox es. ◦ If you specify an invalid value, an exception occurs. ◦ The program catches the exception and displays an appropriate message in a MessageBox. ◦ You can also press the Increment Second Button to add one second to the time. ◦ When you update the time, the program displays the new values of the hour, minute and second in the output1Label and displays the standard and universal times in the output2Label. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

33

34  Time Class Declaration ◦ The application consists of classes Time (Fig. 9.11) and TimeTest (Fig. 9.12). ◦ Class Time declares properties Hour, Minute and Second to control access to instance variables hourValue, minuteValue and secondValue, respectively. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

35  Each of these properties contains a Get accessor and a Set accessor.  The Set accessors perform validation to ensure that the corresponding instance variables are set to valid values; otherwise, they throw an exception and the corresponding instance variable is not modified.  Each Get accessor returns the appropriate instance variable’s value. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

36

37

38

39

40

41  In line 17, notice that we access the argument Time object’s Private instance variables directly with the expressions t.hourValue, t.minuteValue and t.secondValue.  When one object of a class has a reference to another object of the same class, the first object can access all of the second object’s data, methods and properties (including those that are Private ). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

42  The following statements demonstrate how these overloaded constructors can be used: ' use default hour, minute and second Dim time1 As New Time() ' use default minute and second Dim time2 As New Time(2) ' use default second Dim time3 As New Time(21, 34) ' all arguments supplied Dim time4 As New Time(12, 25, 42) ' copy another Time object Dim time5 As New Time(time4)  The first four statements call the constructor in lines 10–13 using varying numbers of arguments.  The last statement calls the constructor in lines 16–18. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

43  Properties Hour, Minute and Second ◦ Properties Hour, Minute and Second are read- write properties—they include both Get and Set accessors. ◦ These enable clients of class Time to get the values of the class’s instance variables and modify them in a controlled manner, respectively. ◦ Because we want client code to be able to both get and set the hour, minute and second, we could have declared the instance variables Public. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

44

45

46

47

48

49

50  Notes on Set and Get Accessors ◦ Although providing Set and Get accessors appears to be the same as making the instance variables Public, this is not the case. ◦ This is another of Visual Basic’s subtleties that makes the language so attractive from a software- engineering standpoint. ◦ If an instance variable is Public, it can be read or written by any method in the program. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

51  A class’s instance variables and methods have class scope.  Within this scope, a class’s members are accessible to all of the class’s other members and can be referenced simply by name.  Outside a class’s scope, class members cannot be referenced directly by name.  Those class members that are visible (such as Public members) can be accessed through a variable that refers to an object of the class (for example, time.Hour ). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

52  The properties we declared in class Time each perform validation to ensure that the hour, minute and second always contain valid values.  For properties that do not have any additional logic in their Set and Get accessors, there is a new feature in Visual Basic 2010— called auto-implemented properties—that allows you to write one line of code and have the compiler to generate the property’s code for you.  For example, if the Time class’s Hour property did not require validation in Fig. 9.11, we could have replaced line 5 and lines 29–41 with  Public Property Hour As Integer © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

53  The compiler would then generate a Private instance variable of type Integer named _Hour and the following property code Public Property Hour As Integer Get Return _Hour End Get Set(ByVal value As Integer) _Hour = value End Set End Property © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

54  Every object you create uses various system resources, including the memory that holds the object itself.  These resources must be returned to the system when they’re no longer needed to avoid resource leaks.  The Common Language Runtime (CLR) performs automatic garbage collection to reclaim the memory occupied by objects that are no longer in use.  When there are no more references to an object, it’s marked for garbage collection by the CLR. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

55  The memory for such an object can be reclaimed when the CLR executes its garbage collector, which is responsible for retrieving the memory of objects that are no longer used, so that the memory can be used for other objects.  Resources like memory that are allocated and reclaimed by the CLR are known as managed resources.  Other types of resource leaks can occur.  For example, an application may open a file on disk to modify the file’s contents.  If the application does not close the file, other applications may not be allowed to use the file until the application that opened the file finishes. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

56  Each object has its own copy of the instance variables of its class.  In certain cases, all objects of a class should share only one copy of a particular variable.  A Shared class variable represents classwide information— all objects of the class share the same variable, no matter how many objects of the class have been instantiated.  Together, a class’s instance variables and Shared variables are know as the class’s fields. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

57  Class Employee with Shared Variables ◦ Our next example uses class Employee (Fig. 9.13) to demonstrate a Private Shared class variable and a Public Shared Property to access that value. ◦ The Shared class variable countValue is initialized to zero by default (line 6). ◦ It maintains a count of the number of Employee objects that have been created. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

58

59

60  Scope of Shared Members ◦ Shared class members have class scope. ◦ A class’s Public Shared members can be accessed via the class name using the dot separator (for example, ClassName. sharedMemberName), as in lines 8, 13 and 18 of Fig. 9.14. ◦ A class’s Private Shared members can be accessed by clients only indirectly through the class’s non- Private methods and properties. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

61  Testing Shared Variables ◦ Class SharedTest (Fig. 9.14) demonstrates the Shared members of Fig. 9.13. ◦ Lines 7–8 use class Employee ’s ReadOnly Shared Property Count to obtain the current value- of countValue. ◦ No Employee objects exist yet, so countValue is 0. ◦ We access Count using the expression Employee.Count. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

62

63

64  Some data needs to be modifiable and some does not.  Constants are fields whose values cannot change during program execution.  To create a constant in a class, declare an identifier as either Const or ReadOnly.  Neither type of constant can be modified once initialized—the compiler will flag as an error any attempt to do so. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

65  Const ◦ A Const identifier must be initialized at compile time in its declaration and can be initialized only to constant values, such as integers, floating-point numbers, string literals, characters and other Const values. ◦ For example, in Fig. 9.8, we used the following Const declaration: ' number of cards Private Const NUMBER_OF_CARDS As Integer = 52 to create a constant representing the number of cards in a deck of playing cards. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

66  The following declaration creates an employeeID constant that might be part of an Employee class: ' unique employee ID Private ReadOnly employeeID As Integer  To initialize the constant employee-by-employee, you can use the constructor: ' initialize constant with constructor argument Public Sub New(ByVal ID As Integer) employeeID = ID End Sub © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

67  Class Math provides a collection of Shared methods that enable you to perform common mathematical calculations.  For example, you can calculate the square root of 900.0 with the Shared method call Math.Sqrt(900.0)  which evaluates to and returns 30.0.  Method Sqrt takes an argument of type Double and returns a result of type Double. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

68  We do not create a Math object before calling method Sqrt.  All Math class methods are Shared and are therefore called by preceding the name of the method with the class name Math and a dot (. ) separator.  Figure 9.15 summarizes several Math class methods.  In the figure, x and y are of type Double.  Methods Min and Max have overloaded versions for several types. © 1992-2011 by Pearson Education, Inc. All Rights Reserved.

69

70  Math Class Constants PI and E ◦ Class Math also declares two commonly used mathematical constants: Math.PI and Math.E. ◦ These values are declared in class Math with the modifiers Public and Const. ◦ The constant Math.PI represents  (3.14159265358979323846)—the ratio of a circle’s circumference to its diameter. ◦ The constant Math.E (2.7182818284590452354) is the base value for natural logarithms (calculated with Shared Math method Log ). © 1992-2011 by Pearson Education, Inc. All Rights Reserved.


Download ppt "Visual Basic 2010 How to Program © 1992-2011 by Pearson Education, Inc. All Rights Reserved."

Similar presentations


Ads by Google