Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Object Oriented Programming I


Published on

A presentation about Object oriented programming

Published in: Technology
  • Be the first to comment

Object Oriented Programming I

  1. 1. VB.NET ITCS 212 Object Oriented Programming I By: Mrs. Marie Tupaz
  2. 2. What is Program, Programming and Basic ProceduresINTRO TO PROGRAMMING
  3. 3. What is Programming? • Program • a set of directions for the computer to complete a task • a sequence of instructions written to perform a specified task with a computer
  4. 4. What is Programming? Programming • process of designing, writing, testing, debugging, and maintaining the source code of computer programs • Wikipedia • giving the computer directions for completing a task
  5. 5. A computer is essentially a trained squirrel: acting on reflex, thoughtlessly runningBack and forth and storing away nuts until some other stimulus makes it do something else. Ted Nelson
  6. 6. What is Programming • Example : • Baking a Cake • Making an Leche Plan
  7. 7. What is Programming? • Basic Task Input Process Output
  8. 8. What is Programming? • Input – Key in data in computer • Process – the task given or work of the program • Output – the results Every Data must be declared before you can use and its called Declaration
  9. 9. What is programming? Baking a Cake: • Declarations : the measuring cups, the measuring spoons, the mixing bowl, and the cake pan. You must make sure you have these before you start. • Input : the ingredients, the cake mix, the eggs, the water, and such. • processing: the mixing and the baking – all the steps needed to turn your ingredients into a cake. • Output : the cake.
  10. 10. Basic Programming Procedure 3 Category • Sequence - order of commands in a program (Washing dishes) • Selection - enable the computer to make decisions : Depending on decision, a different set of directions must be followed (laundry) • Repetition - allow the computer to repeat the same series of steps (Brushing teeth)
  11. 11. Basic Programming Procedure • Program Errors provide computer with precise directions for the task and provide these directions in a language the computer will understand If directions are wrong then the computer makes “mistakes.” How to minimize this mistakes?
  12. 12. Basic Programming Procedure • Algorithm • What is Algorithm? • is a step-by-step procedure • Lit. the description of the steps to solve the problem
  13. 13. Basic Programming Procedure Interface/Instruction = Human/ Computer connection
  14. 14. Basic Programming Procedure Developer/User • Developer - is the person that develops the specifications, designs the program, creates the algorithm, writes the code, and tests the program • User: is the person that uses the finished program. • User part in program designing the program, and testing it
  15. 15. Basic Programming Procedure Design Time/Runtime • Design Time - when the program is developed, the interface is created, and the code is written • Run Time - program is running
  16. 16. Remember At design time a developer decides everything that a program will be and can do. At runtime, the program executes the commands given to it at design time.
  17. 17. Basic Programming Procedure Form/Code • Form window - often called the interface and is what the user sees when the program runs • Code window – where the directions the program is written and must never sees by the user
  18. 18. Basic Programming Procedure • Objects/Events • Objects – controls • Events – the ways a user interacts with the computer
  19. 19. Basic Programming Procedure Code Files/Program • To create or modify a program, you need the project folder and its files. These are used to create the executable file or .exe -- Finished program found in bin folder • .exe –, standalone program that can run even without VS
  20. 20. Short QuizQUIZ #2
  22. 22. Visual Basic.NET • Easier to Use • Streamlined and Modernized • More Powerful than VB 6.0 • Higher level of access to system resources that in the past required the use of languages like C++ • True Object Inheritance • Garbage Collection for better memory management
  23. 23. Visual Studio .NET 2003 • Released April 27, 2003 • J# • Mobile Web Applications: using the integrated ASP.NET Web Forms and the Visual Studio .NET Web Forms Designer, Visual Basic and C# developers can easily build thin- client Web-based applications that render intelligently on more than 200 devices, including wireless application protocol (WAP) phones, wireless personal digital assistants (PDAs), and pagers.
  24. 24. New Web Development • Programming for the Web vs. Windows • New set of controls • Web page layout • ASP.NET • ADO.NET • Mobile Applications • Convert Projects
  25. 25. Just an Upgrade??? • NO! • VB.NET omits quite a few forms of syntax • VB.NET requires a total rewrite rather than a simple port of code • VB.NET is not dependent on older libraries such as VBA runtime and ADO (ActiveX Database Object)
  26. 26. Forms are now Classes • In VB6, forms were classes, but you rarely treated them that way • VB .NET shows the code that instantiates the form • To show additional forms, you must first instantiate them
  27. 27. Form Changes • Forms have undergone a number of changes. These include: • The Forms engine is now WinForms and add such features as docking and opacity • Forms are classes • A Component Tray holds non- visual controls at design-time
  28. 28. VB.NET or C#.NET • C# is a new language that was designed to be friendly to programmers who are already proficient in C or C++ • Either language can be used to write software that takes full advantage of the CLR and .NET framework
  29. 29. NEW IDE
  30. 30. New Tools • Calendar Tool • Date Picker Calendar • Opacity Control • Timer does not lay on form • Command Buttons are now called Buttons • Use ―btn‖ for prefix
  31. 31. Great New Menu Tool
  32. 32. More Changes • The Editor window (formerly the Code window) • Lots more IntelliSense help; can be confusing • Declarations section replaces General Declarations • Collapsible Regions in code (Plus signs)
  33. 33. Collapsed Regions Tabs Method List Class ListCollapsed RegionCollapsedProcedure
  34. 34. General Changes • There have been a number of changes in VB .NET. General changes include: • Form changes • Option Strict • Event Handler changes • Default Properties • Calling Subs and Functions • Boolean operators • Using CTRL + Space to finish variables
  35. 35. The Component Tray • In VB6, controls that were only visible at design-time still appeared on the form in the IDE • Such as the Timer control • VS .NET places controls that are invisible at runtime in a small area below the form • This area is the Component Tray
  36. 36. Forms are now Classes • In VB6, forms were classes, but you rarely treated them that way • VB .NET shows the code that instantiates the form • To show additional forms, you must first instantiate them
  37. 37. The Component Tray • In VB6, controls that were only visible at design-time still appeared on the form in the IDE • Such as the Timer control • VS .NET places controls that are invisible at runtime in a small area below the form • This area is the Component Tray
  38. 38. Calls to Subs and FunctionsRequire Parentheses • In VB6, you called a Sub without parentheses AddOrder OrderNum, OrderDate • You could use the Call statement, which required parenthese Call AddOrder(OrderNum, OrderDate) • .NET always requires parentheses for a Sub, as well as with Functions
  39. 39. New Boolean Operators • The And and Or keywords do not short- circuit in VB and VB .NET • Both sides of an operator are evaluated, even if the first option invalidates the statement • VB .NET adds two short-circuiting Boolean operators: • AndAlso • OrElse
  40. 40. Boolean Operators Example Dim x As Integer x = 0 If x>2 And 5x > 1 Then ... • This If statement is already false on the x>2 part, but 5x is still checked because And does not short-circuit • In this case, 5x causes a ―divide by zero‖ error
  41. 41. Boolean Operators Example cont. Dim x As Integer x = 0 If x>2 AndAlso 5x > 1 Then ... • This If statement is already false on the x>2 part, so the AndAlso does not check the 5x portion • The key result: No Error!
  42. 42. The Value of True • The value of True has not changed • Originally, the value of True was going to change, but it did not • The value of True in VB .NET is still negative one (-1) • Your code should not check for -1, but for True
  43. 43. Common Language Runtime • VB.NET has undergone a significant overhaul to accommodate the CLR • New object oriented design features • Much higher levels of type safety • Universal type system allows for greater inoperability
  44. 44. Changes in Properties • The Alignment property becomes TextAlign • The maximum length of identifiers is 16,383 • All new Help — MSDN • OptionButton becomes RadioButton • Frame becomes GroupBox • New component tray holds non-visible controls
  45. 45. More Property Changes • Text boxes have a Clear method txtName.Clear() txtName.Text = ―‖ • Focus method replaces SetFocus txtName.Focus() • Many colors available through the Color class • lblMessage.ForeColor = Color.Blue Color.Aquamarine Color.Bisque Color.Chocolate Color.Cadetblue
  46. 46. Tab Order This is neat! Click on View and Tab Order
  47. 47. Caption / Text Property • VB 6.0 - Some controls, such as Label, have a Caption property that determines the text displayed in or next to the control. Other controls, such as TextBox, have a Text property that determines the text contained in the control • VB.NET - In Windows Forms, the property that displays text in a control is consistently called Text on all controls. This simplifies the use of controls.
  48. 48. VB.NET IDE • Form Window • form window default name is Form1 • Here you add controls to create the user interface. • Toolbox • contains the controls used to build the user interface
  49. 49. VB.NET IDE • Solution Explorer • contains a list of files and forms in your project • Properties Window • list of properties for each control. • The column on the left contains the names of the properties for that control. • The column on the right contains the settings for the properties.
  50. 50. VB.Net IDE • Naming Controls • Controls are identified by their names • Rules for naming controls • Names must start with a letter. • name can contain any combination of letters, numbers, or underscores ( ). • Name Cannot contain spaces. • Avoid using any special characters. • Names can be more than 1,000characters but limit it with twenty characters. • start all controls with a three-character prefix to identify the type of control
  51. 51. VB.Net IDE – Naming Controls
  52. 52. VB.Net IDE • Code Window • Where the program code is written • To view right click on the form and select View Code object the popup or double-click on the object • Example • Double-click on the Button • That opens the Code Window and creates a procedure and will create event
  53. 53. VB.Net IDE • Code Window • procedure is a block of code that completes a particular task. Private Sub … End Sub. • Event • When you double-clicked on the Button, it created a click event for that Button
  54. 54. Use and ParsingDATA TYPES
  55. 55. Data Types byte 1 byte Range Unsigned 0 to 255 byte sbyte 1 byte Range Signed -128 to 127 byte Short 2 Range Signed (sho) bytes -32768 to 32767 short ushort 2 Range Unsigned bytes 0 to 65535 short
  56. 56. More Integer Data Types int 4 bytes Range Signed -2,147,483,647 to (int) 2,147,483,647 integer uint 4 bytes Range Unsigned 0 to 4,294,967,295 integer long 8 bytes Greater than Signed (lng) 900,000 trillion long int ulong 8 bytes Greater than 18 Unsigned million trillion long int
  57. 57. Other Data Typessingle 4 Range Float(sng) bytes A number 6 digits past number the decimaldouble 8 Range Double(dbl) bytes A number 14 digits past precision the decimaldecimal 8 Range Fixed bytes A number 28 zeros long precisionstring (str) N/A Range N/A Unicodechar 2 Range Unicode bytes 0x0000 to 0xFFFF characterBool (bln) True or False Boolean
  58. 58. Data types
  59. 59. Data types
  60. 60. Converting Data Types • Initialize a variable at declaration Dim intMax As Integer = 100I Dim decRate As Decimal = 0.08D • Declare multiple variables at once Dim intCount, intNum As Integer • Convert all input to correct data type (Do not use Val function) decSale = CDec(txtSale.Text) • CInt (still rounds to even #) • CDec • CStr ** CInt and CDec parse some characters like $, commas,()
  61. 61. Format • VB 6.0 – Format(variable, ―Currency‖) • VB.NET – FormatCurrency(variable) FormatPercent(variable) FormatNumber(variable) FormatNumber(variable,3) FormatDateTime(variable)
  62. 62. Changes in Syntax • Currency • Replaced with Decimal in VB.NET • The Currency data type (64 bit) does not provide sufficient accuracy to avoid rounding errors, so Decimal (96 bit) was created as its own data type. • Dim x As Currency is upgraded to: Dim x As Decimal
  63. 63. Long and Integer Data Types • VB 6.0 - Long variables were stored as 32-bit numbers and Integer variables as 16-bit numbers • VB.NET - Long variables are stored as 64-bit numbers, Integer variables are stored as 32-bit numbers, and Short variables are stored as 16-bit numbers.
  64. 64. Variant Data Type • From Variant data types to Object • due to keeping all the languages more similar. This is no longer the same as a pointer to an object. • Dim x As Variant is upgraded to: Dim x As Object
  65. 65. Object Data types • Object supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. It is the root of the type hierarchy. • Everything inherits from Object-everything. • The Object data types make VB.NET better but they also make your programming easier.
  66. 66. Object Data types • 7 methods of Object: • Equals(Object) as Boolean • Equals(Object, Object) as Boolean • GetHashCode() as Integer • GetType() as System.Type • New() • ReferenceEquals(Object, Object) as Boolean • ToString() as String
  67. 67. Object Data types • If you look at another data type such as Char in the VB.NET Object Browser, youll see six of the seven methods are also available. • The missing one is the constructor method, New(). This is taken care of when a variable is declared.
  68. 68. Object Data types • VB 6.0 • If (UCase(chrl) >= "A" And UCase(chrl) <= "Z") Then ... • to find out if a one character string is actually a letter. • VB.NET, • If Char.IsLetter(myCharVar) Then ...
  69. 69. Option Explicit • Option Explicit { On | Off } • In VB.NET the option is turned on by default for all new projects. • When Option Explicit Off is used (not a good programming style), you can use any variable without first declaring it.
  70. 70. • To Set 1. On the Tools menu, choose Options. 2. Open the Projects and Solutions node. 3. Choose VB Defaults. 4. Modify the Option Explicit setting. 5. To set Option Explicit on the command line 6. Include the /optionexplicit compiler option in the vbc command.
  71. 71. • Example• In this example Option Explicit statement use to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time.
  72. 72. Force explicit variable declaration. • Option Explicit On • Dim thisVar As Integer thisVar = 10 thisInt = 10 causes ERROR
  73. 73. Option Strict On • New Option in VB.NET • When Option Strict is turned on, the compiler/editor does not allow implicit conversions from a wider data type to a narrower one, or between String and numeric data types • When you use the Option Strict statement, the statement must appear before any other code
  74. 74. Option Strict On • Option Strict also generates an error message in the following scenarios: • For any undeclared variable. This is because Option Strict also implies Option Explicit. • Late binding. • If Option Strict is Off we can convert the value of Long to an Integer. • Limits erroneous numbers or run-time errors
  75. 75. Option Strict On • Example • Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum MsgBox(intNum) End Sub End Class
  76. 76. Case Conversions • String ToUpper and ToLower methods • Replace UCase and LCase functions • If txtInput.Text.ToUpper = ―YES‖
  77. 77. New Compound Operators • New assignment Operators • += –= *= /= = &= • decTotal += decSale same as decTotal=decTotal + decSale
  79. 79. Creating variables • Variable • a storage container for your data • Declaration –creation of variable or declaring a variable • Assignment – change the value in a variable • Syntax • Dim varName As Type • Declaration Example • Dim shoTest as Short
  80. 80. Creating variables • Variable • initializing a variable • You must initialize a variable at the same time you declare it • Example • Dim shoCaseSize As Short = 24 • Dim strLastName As String = "Jefferson― Remember : When you assign a value to a variable, you must make sure it can store the answer
  81. 81. Creating variables • Different assignment of variable • Use an assignment statement to place a value in a variable • shoTestScore = 88 • assigning the value of one variable to another • strNewAddress = strOldAddress • using a mathematical equation • shoTotal = shoNum1 + shoNum2 • shoTotal = shoNum1 + 10
  82. 82. Mathematical Operations
  83. 83. Rules of Precedence • what’s in parentheses first and work your way out, • exponentiation before other mathematical calculations, • multiplication and division from left to right, and then • addition and subtraction from left to right.
  84. 84. Rules of Precedence • Example • sngAverage = (shoTest1 + shoTest2 + shoTest3 + shoTest4)/4 • 175=3 • 17 Mod 5 = 2 • 17^5
  85. 85. Creating Constants • Constants are like variables except their values cannot be changed while the program is running • Example • Const sngSalesTaxRate As Single = 0.05 • Const strTitle As String = "A Tale of Two Cities"
  86. 86. Creating Constants • What is wrong with each of the following? • shoNum + shoNum2 = shoTotal • shoNum = 10∗4 • Dim decPrice As Decimal = "$4.99" • shoCube = (shoSide)3
  88. 88. Block-Level Scope • VB .NET introduces variables that only exist within blocks of code • Blocks are items such as For…Next, Do…Loop, and If Then…End If • Variables are only visible within the block, but their lifetime is that of the whole procedure
  89. 89. Block-Level Scope • For Loop • enable us to execute a series of expressions multiple numbers of times. For loop needs a loop index which counts the number of loop iterations as the loop executes.
  90. 90. For loop • syntax • For index=start to end[Step step] [statements] [Exit For] [statements] Next[index] • Example Dim i As Integer For i = 1 To 10 Console.WriteLine(i) Next
  91. 91. Do.. Until • Do...UNTIL Loop • is a loop that runs until the loops condition is true, the condition being checked after each iteration of the loop. • Syntax • Do statements Loop Until condition
  92. 92. Do.. Until • Example Do Until i > 10 Console.WriteLine(i) i=i+1 Loop
  93. 93. Do...Loop While • Do… While loop: A Do...Loop While loop runs until the loops condition becomes false. Its condition is checked after each iteration of the loop.
  94. 94. Do...Loop While • Syntax • Do statements Loop While condition • Example Shows the DO while Loop: Do Console.WriteLine(i) i=i+1 Loop While i < 10
  96. 96. Arrays • VB 6.0 - Arrays can be defined with lower and upper bounds of any whole number. The Option Base statement is used to determine the default lower bound if a range is not specified in the declaration. • VB.NET- To enable interoperability with other languages, all arrays must have a lower bound of zero. This makes the Option Base statement no longer necessary. • Dim a(1 To 10) As String is upgraded to: Dim a(10) As String
  97. 97. Array Size • This is one area that was going to change, but did not • When you declare an array, it starts at zero, and the element number you use is the Upper Bound of the array • This means that arrays will always be one larger than the size declared • Dim x(2) As Integer has three elements
  98. 98. While Loops • VB 6.0 - While statements are ended with a WEND statement. • VB.NET - WEND statements are changed to End While. This improves language consistency and readability. • It executes a block of statement as long as condition is true.
  99. 99. While Loops • syntax: • While condition statement-block End While • Example While i < 10 Console.WriteLine(i) i = i + 1 // same with i+=1 or i++ End While
  100. 100. Arrays Continued • Arrays in VB.NET are classes supporting properties and methods, making them quite flexible. • .Sort • .Reverse • You can sort an array in one line of code!
  101. 101. VB 6.0 to VB.netOTHER CHANGES
  102. 102. Parameter Passing • VB 6.0 - Parameters that do not specify either ByVal or ByRef default to ByRef • VB.NET - Parameters that do not specify either ByVal or ByRef default to ByVal. Defaulting to ByVal rather than ByRef eliminates the problem of having a procedure mistakenly modify a variable passed in by the caller.
  103. 103. GoSub, On Goto • VB 6.0 - The GoSub line ... Return statement branches to and returns from a subroutine within a procedure. • VB.NET - GoSub...Return is a nonstructured programming construct. Its use makes programs harder to read and understand. Creating separate procedures that you can call may provide a more structured alternative or use case statements.
  104. 104. Structures Replace UDTs • User Defined Types (UDTs) have been replaced with Structures • Structures are far more powerful than UDTs • They support the equivalent of properties and methods • They are not as powerful as classes
  105. 105. File I/O Changes • VB .NET supports such built-in functions as FileOpen and Write • These functions are found in the Microsoft.VisualBasic namespace • VB6 code that is upgraded to VB .NET will use these functions • The Framework includes a rich namespace called System.IO
  106. 106. The System.IO Namespace • System.IO contains a large number of classes for handling all types of I/O • There are a variety of major categories of objects in System.IO • These include objects to manage files and directories, read and write text files, and read and write binary streams
  107. 107. Working with Files • FileInfo and DirectoryInfo classes are for such operations as creating, moving, and deleting files and directories • If you use the Open method of FileInfo to open a file, the returned object is a FileStream
  108. 108. Reading and Writing Files • The StreamReader and StreamWriter classes are common ways to perform file I/O • This can read binary and text data • The StringReader and StringWriter are designed to read text data
  109. 109. Structured Error Handling • VB .NET now supports Structured Exception Handling (SEH) • On Error Goto is still supported • SEH uses the Try…Catch…Finally syntax • Should help reduce spaghetti code
  110. 110. Overloading • Overloading is the ability to have the same method, but with different arguments • You could fake this in VB6 using ParamArrays • For example, a FindCustomer method could accept a customer ID, a customer name, or a contact name
  111. 111. Constructors and Destructors • Constructors are blocks of code that run when a class is instantiated • Destructors are blocks of code that run when a class drops out of memory • Constructors can be overloaded to make them more powerful • Due to garbage collection, you cannot be assured of when destructors will execute
  112. 112. Dispose and Finalize • Finalize will run when the object is cleaned up by the GC • You might want to release resources explicitly, since you cannot determine when Finalize will be called • Use the Dispose design pattern to explicitly free resources
  113. 113. Multithreading • VB .NET allows you to create truly multithreaded (or free threaded) applications • The Framework includes a System.Threading namespace to make working with threads easier • You will learn more in Chapter 11, ―Multithreaded Applications‖
  114. 114. Windows VB.NET Example
  115. 115. Activity #1TUITION CALCULATOR
  116. 116. Activity # 1 - Tuition Calculator
  117. 117. Activity # 1 - Tuition Calculator • TuitionCalculator Code • Public Class frmTuitionCalculator • Private Sub btnExit_Click(ByVal sender As System.Object, • ByVal e As System.EventArgs) Handles btnExit.Click • End • End Sub • Private Sub btnTuition_Click(ByVal sender As • System.Object, ByVal e As System.EventArgs) Handles • btnTuition.Click • Dim shoCredits As Short • Dim decTuition As Decimal • shoCredits = txtCredits.Text • decTuition = shoCredits * 100 • lblTuition.Text = decTuition.ToString • End Sub • End Class
  118. 118. Keywords and Terms
  119. 119. Keywords and Terms
  120. 120. Keywords and Terms
  121. 121. Keywords and Terms
  122. 122. Keywords and Terms
  123. 123. Quiz # 3LONG QUIZ
  125. 125. Errors in Your Program • Syntax errors spelling or usage errors in your code. Computer doesn’t understand what you’ve written. • Logical errors • errors in your thinking. The computer understands the commands, but the ―what to do‖ or ― how to do them‖ is different than what you were expecting. • Runtime errors • Problems that crash a program.
  126. 126. Creating Vb. Simple programVB.NET AT WORK
  127. 127. Activity # 1 - Tuition Calculator
  128. 128. Activity # 1 - Tuition Calculator • Procedure for creating the program • Form Window 1. In every System you must first to create the user interface and add all the control needed 2. name all the controls 3. Choose the control that will trigger the event and go to code window Note: Design should follow later after the program works
  129. 129. Activity # 1 - Tuition Calculator • Procedure for creating the program • Code Window
  130. 130. Activity # 1 - Tuition Calculator • TuitionCalculator Code • Public Class frmTuitionCalculator • Private Sub btnExit_Click(ByVal sender As System.Object, • ByVal e As System.EventArgs) Handles btnExit.Click • End • End Sub • Private Sub btnTuition_Click(ByVal sender As • System.Object, ByVal e As System.EventArgs) Handles • btnTuition.Click • Dim shoCredits As Short • Dim decTuition As Decimal • shoCredits = txtCredits.Text • decTuition = shoCredits * 100 • lblTuition.Text = decTuition.ToString • End Sub • End Class