Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET

Size: px
Start display at page:

Download "Unit Title: Objects in Visual Basic.NET. Software Development Unit 4. Objects in Visual Basic.NET"

Transcription

1 Software Development Unit 4 Objects in Visual Basic.NET Aims This unit proceeds to the heart of object-oriented programming, introducing the mechanisms for creating new classes of object, defining their composition and describing how they are deployed (as object) in programs. By studying this unit, you should acquire the practical skills necessary to create and use simple objects in programs. University of Paisley Page 1 of 21

2 Objectives In this unit you will learn: How to create a new Class of Objects in a Visual Basic program How Objects are used in object-oriented programs How to use Value types and Reference types, and how to convert one type to the other How to make use of the properties and methods of a variable or object University of Paisley Page 2 of 21

3 TABLE OF CONTENTS 1 CLASSES CLASS METHODS Class Properties Constructors Overloaded Constructors The Class Interface Responding to Conditions Class Events OBJECT -ORIENTATION AND VARIABLES Value Types and Reference Types Manipulating Value and Reference Types Distinguishing Value and Reference Types REVIEW QUESTIONS SOLUTIONS TO EXERCISES ANSWERS TO REVIEW QUESTIONS...21 University of Paisley Page 3 of 21

4 1 Classes A Class is a design for a specific type of object. Every variable in a.net program is an object or provides access to one, and by creating a class, we create the potential for one or many objects with specific characteristics and behaviours. We can create a class easily in VB: Module NewClass Public Class BankAccount Public AccountName As String Private Balance As Integer End Class Dim MyObj As BankAccount = New BankAccount() End Module Listing 4.1: A class definition, and an object declared in The only statement in Sub Main in listing 4.1 creates an object of the class BankAccount. In this statement, two things are being done: 1. A variable, MyObj, is being dimensioned to hold a member of the class (Dim As, much as for any type of variable) 2. A new object of the class is being created ( = New...), and assigned to the newly dimensioned variable to initialize it Note that this implies there are two components to creating an object of a class the variable that we use to access the object, and the object that is created separately and assigned to the variable. There will be more on this later. Within the object code, note the use of the words Public and Private. A public member of a class can be accessed from code that uses an object of the class. For example, we could in Sub Main refer to MyObj.AccountName, since AccountName is a public member. A private member can not be accessed by code using the object (a statement referring to MyObj.Balance would be an error, and Visual Basic would reject it when compiling the project). Public and Private scope can be applied to many constructs in a VB program: classes, member variables, class properties and methods can all be defined as public (accessible from outside an object) or private (invisible from outside and object). Note that the term member variable is used to describe the Private and Public variables declared within a class, and signifies that each member (or object) of the class will have its own copy of these variables. Consider the following alterations to, which adds a couple of statements that make use of the new BankAccount object: Dim MyAccount As BankAccount = New BankAccount() MyAccount.AccountName = "John Smith" MyAccount.Balance = 100 'Error; Private member variable. Listing 4.2: Using the class (unsuccessfully) If you attempt to enter the shown in the same module as the class definition, two things will indicate that this code is wrong. Firstly, when you enter the MyAccount. in the last statement, the pop-up list of class members will not offer to provide you with the Balance member, indicating that it is not accessible at this point. If you persist, typing the University of Paisley Page 4 of 21

5 member name manually, Visual Studio will underline the statement with a wavy blue line, indicating that this is a syntax error. A third indication will appear if you try to run the program the following error report: Figure 4.1: The error report from trying to access a private member By making the Balance variable in an account object Private, we can control access to it, which is of course a useful thing to do with the balance of a bank account, since we can prevent unauthorised access. Of course, if we define a private variable in a class, there must be some way of using it if it is not to be a useless waste of space. For this we need class methods. Exercise 4.1 Add two new member variables to the BankAccount class: one Private member variable called PIN (short for Personal Identification Number), and one Public member variable called AccountNumber. 1.1 Class Methods Classes (and Structures) can contain blocks of program statements, organised as Subs or Functions (of which more later). These are collectively known as the class s methods, and allow us to define how objects of the class can be made to behave in a program. We can add a method to a class by adding a new Sub or Function, as shown in Listing 4.3: Public Class BankAccount Public AccountName As String Private Balance As Decimal Public Sub Deposit(ByVal Amount As Decimal) Balance += Amount Public Function GetBalance() As Decimal Return Balance End Function End Class Listing 4.3: Adding methods to the class In the above class definition, Sub Deposit(),will add a given amount to the current value in Balance (+= adds to the variable on the left). The amount to be added is named in the brackets after the Sub s name: this will act as a placeholder for any amount that is given to the Deposit method. Any statement calling (executing) the method will have to include an amount, either as a literal value, or in a variable of the correct type (Decimal). If a call to the method omits the amount or includes a variable of the wrong type, this will be an error. The second is a Function, GetBalance, which will return the current contents of Balance (i.e. it will, when called, be equivalent to the actual value specified in the Return statement). A Function is a special type of method that returns some value to the statement that called it. A function is defined to return a specific type of data (e.g. Decimal here) and so any method that is defined as a Function within an object can be used in any place a literal value of the same type could be. Note that these Public methods both provide access to the Private member variable Balance. The power of object-oriented programming lies in our ability to provide controlled access to private data through public methods. We can now use the class s methods in any code that works with the class. For example: Dim MyAccount As BankAccount = New BankAccount() University of Paisley Page 5 of 21

6 MyAccount.AccountName = "John Smith" Console.WriteLine("Account name:{0}", MyAccount.AccountName) Console.WriteLine("Account balance:{0}", MyAccount.GetBalance) MyAccount.Deposit(100) Console.WriteLine("Account balance:{0}", MyAccount.GetBalance) Listing 4.4: Using an object s methods Running listing 4.4 will result in the following console output: Exercise 4.2 Figure 4.2: The result of running listing 4.4. A Person class is to have member variables for storing Name, and DateOfBirth of an individual. Write code to define this class, and write a statement in a Sub Main( ) to create an instance of the class (remember to use New). Add a function method that will return the person s age in years (use the DateDiff function to return the number of years between DateOfBirth and the current date, given by the Date function look these up in Help). Test this method by setting the DateofBirth member to some date and using Console.WriteLine( ) to display the result of the method Class Properties An alternative to providing Subs and Functions to access private member variables is to create a Public Property. For example, in BankAccount, we can create a CurrentBalance property that would access the Balance variable as follows: Public Property CurrentBalance() As Decimal Get Return Balance End Get Set(ByVal Value As Decimal) Balance = Value End Set End Property Listing 4.5: A property definition for BankAccount The Get part of a property acts as a function, returning a result through the property name. The Set part acts as a Sub with a single, allowing a value to be passed into the object (to, for example, change the data in a Private member variable). Program statements that use this property look exactly like the program statements that would access a Public member variable called CurrentBalance: MyAccount.CurrentBalance = 100 Console.WriteLine(MyAccount.CurrentBalance) The above statements would assign 100 to the Balance private member variable, and then get the new value to display on the console. To all intents and purposes, this is just like making the Balance member variable public. We can exercise more control on an internal member variable by hiding it behind a property in this way. For example, we can create CurrentBalance as a read-only property, by adding the keyword ReadOnly to the title and removing the Set part: University of Paisley Page 6 of 21

7 Public ReadOnly Property CurrentBalance() As Decimal Get Return Balance End Get End Property Listing 4.6: Creating a read-only property. It is also possible to create a write-only property (using the keyword WriteOnly in place of the current ReadOnly one). The choice of read/write (the default), read-only and write-only allows us to provide very precise control in the code that accesses member data. A property can also be used to create the illusion of member variables that do not even exist. Consider the following example class: Public Class Circle Public Radius As Single Public Property Diameter() As Single Get Return 2 * Radius End Get Set(ByVal Value As Single) Radius = Value / 2 End Set End Property End Class Listing 4.7: Creating a property out of thin air Here, Radius is a real value stored as a member variable. Diameter is calculated directly from the value in Radius. The combination of both allows us to hide how the actual size information of the Circle class is implemented. We could easily do the arithmetic of this trick directly in the program code that works with a Circle object. However by making the circle class appear as if it has a diameter member, we are improving the class in several ways: Users can access and change the value of the diameter easily The radius value can be accessed just as easily as before the Diameter method was added Members of the class do not need the extra storage space required for a Diameter variable. Although this may seem initially to be at best a minor saving - one member variable replaced by a chunk of code in most circumstances the saving will be very real. Each object of the class will save the space the member variable would have taken up, and yet will require no additional space for the property, which is part of the class, not its objects. A single class can be responsible for a great many objects, and therefore a single property can free up a lot of storage space Most importantly, by NOT storing the diameter as a variable, there is no chance of the member variables having values that are inconsistent with each other e.g. a Radius of 10 and a Diameter of 2. Exercise 4.3 Return to the Person class written for exercise 4.2. Delete the Name member variable, and replace it with two other member variables, FirstName and LastName. Now create a FullName, read-only property that combines both first and last names remember to include a space between first and last names. Test the property in Sub Main Constructors A constructor is a sub that sets up a new object. Constructors are defined in the class so that objects are created in a controlled way. For example, since there is no such thing as a circle with a zero radius, we could add a constructor to the class to ensure that as one is created, it must take on a radius: University of Paisley Page 7 of 21

8 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 Public Property Diameter() As Single Get Return 2 * Radius End Get Set(ByVal Value As Single) Radius = Value / 2 End Set End Property End Class Listing 4.8: Adding a Constructor method (New()) A Constructor method can therefore serve to set up an object into a safe state as soon as it is created. To return to the BankAccount example, we can use a constructor to set up an account so that it must have an owner (an AccountName is required). Public Class BankAccount Public AccountName As String Private Balance As Decimal Public Sub New(ByVal Name As String) AccountName = Name Public Sub Deposit(ByVal Amount As Decimal) Balance += Amount Public Function GetBalance() As Decimal Return Balance End Function End Class Listing 4.9: Adding methods to the class Now we can create a BankAccount that belongs to someone immediately: Dim MyAccount As BankAccount = _ New BankAccount( Fred Bloggs ) or... CustName = Fred Bloggs Dim MyAccount As BankAccount = _ New BankAccount(CustName) Note that we can invoke the constructor in the same statement as we initialize the reference variable. We can pass as many arguments (values) as we wish to a constructor, separating each with commas, so it would be possible to have the BankAccount constructor accept two values, the Name of the account and its initial balance: Public Sub New(ByVal Name As String, ByVal Initial As Decimal) AccountName = Name Balance = Initial University of Paisley Page 8 of 21

9 Exercise 4.4 The Person class would benefit from a constructor. Create a New( ) method for the class, including First and Last names, , and DateOfBirth as parameters. Test this in a statement in Sub Main Overloaded Constructors Overloading is a facility that allows us to define more than one version of a Sub or Function, where the different versions were distinguishable by the number or types (or both) of parameters accepted. This turns out to be useful for constructors, where different ones can be set up to accept different combinations of data:: Dim MyAccount As BankAccount _ = New BankAccount( Fred Bloggs ) would invoke the constructor defined to accept a Name argument, while calling: Dim MyAccount As BankAccount _ = New BankAccount( Fred Bloggs,100) would invoke the second version that also accepted a value for the initial balance (if one were defined). This can greatly simplify the use of a class in programs The Class Interface The combination of Public member variables, properties, subs and functions is often referred to as the class interface. In Visual Studio, we are constantly reminded what the interface for a class we are using is, since if we type the identifier of an object followed by a dot, a list of interface members pops up. In object oriented programming, we consider two specific facets of any class/object. Every class has an Interface (which we now know to be the set of public members) and an Implementation (which is the actual class code (including the interface elements) that defines how the class works. Separating these two aspects, so that users can access the class interface, but only the class s developer can see its implementation, is a very important principle in object oriented programming encapsulation Responding to Conditions When we create a class, we are able to define how it will work (its implementation) and how users of the class (i.e. other programmers) will see it (the interface). We can add greater control to how an object responds to interactions by making certain operations conditional. For example, consider what happens when a user (a program statement) withdraws cash from a bank account. If the account has 50 in it, and the withdrawal is 50 or less, this does not cause a problem. However, what if the withdrawal is 100 (the account does not have enough balance to cover this. We can add a conditional statement to handle this: Public Sub Withdraw(ByVal Amount As Decimal) If Amount <= Balance Then End If Balance -= Amount Listing 4.10: Adding a Withdraw method The first statement in the Withdraw method acts as the start of a control structure that governs one or more other statements. If the enclosed condition (Amount <= Balance) evaluates as True, the controlled statement is executed. If it is False, the controlled statement is ignored. We will go on to look at control structures in more detail in the next chapter. University of Paisley Page 9 of 21

10 1.1.6 Class Events One final (for now) facet that we can add to the development of a class is to make it respond in some user-defined way to interactions. This may initially seem to be an odd facility we are already controlling objects of a class by writing program code: what other facilities are needed. However, we must think of a class as a new type of thing in a program. Even though we can put a lot of effort into building a class, we can never anticipate exactly how it will be used. A programmer who uses a class may want to organise it so that whenever something is done to an object, the object can respond automatically. For example, in the previous section, was saw how we could impose control on a withdrawal from a bank account by adding some conditional processing (if..then). What if we wanted to allow the programmer who was using the class to say what happened when an attempt to over-draw from an account. It could be that the withdrawal was not allowed (as shown in listing 4.10), or it could be that a bank would prefer to allow an overdraft since they will make money from it. Even as the creator of the class, we can t really dictate how it might be used in a given situation. For this, we can add Events to a class. An Event is a signal from within an object, which can be a simple signal that states something happened, or a more informative signal that can also provide some data regarding what has happened: Public Event Overdrawn(ByVal Amount As Decimal) 'Other code... Public Function Withdraw(ByVal Amount As Decimal) mvarbalance -= Amount If Balance < 0 Then RaiseEvent Overdrawn(mvarBalance) End If End Function Listing 4.11: A modified Withdraw method that makes banking sense. In listing 4.11, an Event, Overdrawn, has been declared. It will incorporate an indication of the amount the account is overdrawn by. When a transaction is made that will overdraw the account, RaiseEvent causes the signal to be sent to whatever code is listening for it. If the Event is not to be ignored, some Sub must handle it. An Event Handler is a Sub that has been set up to respond to a specific event. When the event occurs, the Event Handler will execute: Private WithEvents Account As BankAccount 'Other code... Sub DealWithOverdraft(ByVal Amount As Decimal) _ Handles Account.Overdrawn Console.WriteLine("Account is overdrawn by : {0}", Amount) Listing 4.12: An object WithEvents, and an Event Handler Note that in Listing 4.12, the BankAccount object has been declared WithEvents. This lets the.net runtime know that it must look out for signals from this object. The first line of Sub DealWithOverdraft declares that this sub will handle the Overdrawn event from that object. This tells the.net runtime to associate the Overdrawn signal from Account with this Sub. Since the DealWithOverdraft method can be written by a user of the class (it does not have to be the programmer who created it), If at a later date it is decided that an account going into overdraft requires a different type of action, there will be no need to change the coding of the BankAccount class, only the event handler. Listing 4.13 shows the full implementation of the BankAccount class, incorporating all of the partial examples so far. Module Bank Public Class BankAccount Public AccountName As String University of Paisley Page 10 of 21

11 Private Balance As Decimal Public Event Overdrawn(ByVal Amount As Decimal) Public Sub Deposit(ByVal Amount As Decimal) Balance += Amount Public Function Withdraw(ByVal Amount As Decimal) Balance -= Amount If Balance < 0 Then End If End Function RaiseEvent Overdrawn(Balance) Public ReadOnly Property CurrentBalance() _ Get End Get End Property End Class Return Balance As Decimal Private WithEvents Account As BankAccount Sub DealWithOverdraft(ByVal Amount As Decimal) _ Handles Account.Overdrawn Console.WriteLine("Account is overdrawn by : {0}", _ Amount) BankAccount = New BankAccount() Account.AccountName = "John Smith" Console.WriteLine("Account name: {0}", _ Account.AccountName) Console.WriteLine("Account balance: {0}", _ Account.CurrentBalance) Account.Deposit(100) Console.WriteLine("Account balance: {0}", _ Account.CurrentBalance) End Module Listing 4.13: The full BankAccount class and code to test it. 1.2 Object-Orientation and Variables Visual Basic.NET and the other.net languages are fully object-oriented. As such, their core principle is that everything in a program is an object or part of an object. A consequence of this is that all of the existing data types that exist in the Common Type System (CTS) have additional properties and behaviours associated with them. e.g.: Dim i As Integer = 42 Console.WriteLine( _ University of Paisley Page 11 of 21

12 "Min value = {0}, Max value = {1}", _ i.minvalue, i.maxvalue) Listing 4.14: Using an Integer variable s methods Any integer variable (or even a simple value, like 42), is able to provide operations and properties associated with the Integer class. Intellisense within Visual Studio is one useful consequence, and a good illustration, of this. Enter a dot. after a variable s name, and up pops a list of interface members: Figure 4.3: Intellisense pop-up code assistance in the Visual Studio IDE. However, although everything in.net is an object, the simple types available from the CTS are special cases. In the more general case, objects are defined in a class, and since they are not native to the common language runtime,.net can make no assumptions about them. If you declare a variable of type Object and immediately try to reference its GetType method, your program will crash unceremoniously. The first code snippet shown below illustrates this: Dim i As Integer Dim o As Object Console.WriteLine(i.GetType()) Console.WriteLine(o.GetType()) 'This line causes an error. Listing 4.15: Wrong use of an object type When the console program that contains the above code is executed, the error message shown in figure 4.4 is the result. Note that before the error message, the data type of the integer i is properly reported (System.Int32 is the data type in the Common Type System that Visual Basic calls Integer). Figure 4.4: The result of executing listing 4.15 This problem does not occur with the simple types. The error occurs because the variable o is an Object type. Proper use of an Object type (or anything that has been defined in a class) requires us to create a new instance of it before we try to access any properties and methods: Dim i As Integer Dim o As Object = New Object() Console.WriteLine(i.GetType()) University of Paisley Page 12 of 21

13 Console.WriteLine(o.GetType()) 'No error; the object exists. Listing 4.16: Proper use of an Object type The difference is that simple variables (sometimes referred to as the primitive types or simply primitives) are implemented in such a way that a variable directly accesses the memory locations at which it is stored, while other variable types (classes) are used to refer to objects stored separately in an area of memory the CLR reserves for objects. The first type is called a Value Type object, while the second is a Reference Type. Dim i As Integer 0 Dim a As BankAccount a = New BankAccount... Nothing BankAccount object Figure 4.5: A value object (i) and a reference object (a) Value type objects inherit from the System.ValueType class. The key feature of a reference type is that the variable does not contain the object, but simply knows where to find it (as shown in figure 4.5) if one exists. If a reference variable does not refer to an object, it refers to Nothing, a valid Visual Basic keyword. Any attempt to access a property or method of a reference variable that refers to Nothing will cause a NullReferenceException as described in the error report in Figure 4.4. Exercise 4.5 Using the Person class you created in previous exercises, amend the code in Sub Main so that the keyword New is not used to create a Person object. Observe the results of this when you attempt to run the code (you should be expecting an error) Value Types and Reference Types A ValueType variable contains data. The implications of this are profound: every ValueType variable is independent of every other one, and since the data is tightly bound to the variable, ValueType variables can be operated on very efficiently. When a ValueType is created by a Dim statement within a Sub definition, the memory that stores the variable s value can be accessed directly by the code in the Sub. X As Integer 42 Figure 4.6: A Value Type variable A Reference variable on the other hand is stored in memory that is separate from the program code that operates on it. Basically, the variable is an indication of where the data that belongs to it lives its address in memory. To operate on the data, program code must follow the reference to the object. This takes time and therefore reference types are less efficient to deal with. The difference in efficiency is minor, but in a program that deals with a large number of variables, small time differences can mount up. University of Paisley Page 13 of 21

14 O As Object O s Data Figure 4.7: A Reference variable and its object The distinction exists because Microsoft have created the most efficient possible implementation of all the value types (which are those most frequently used in programs) by giving them direct access to values. Class types (including classes in the CLR like ArrayList, Form etc.) are implemented less efficiently but with more flexibility (we can extend a class type by inheritance) Manipulating Value and Reference Types There are several consequences of the distinction between value types and reference types that affect the way that we can manipulate them in program code: A ValueType always has a value from the point of its declaration, since a newly created ValueType variable is automatically assigned a zero value if it is not initialized. Conversely, a Reference type is assigned the value Nothing when it is declared if it is not initialized this effectively means no object Value types are processed more efficiently than reference types When a value type is copied by assignment, a new, independent copy is made. When the original value is altered, this has no effect on the copy, which retains the value first assigned until its value is altered specifically. When a reference value is copied by assignment, the new variable is made to refer to the same object as the first. Therefore, any change to either variable s object will be reflected in the other, since there is only one object referred to by two variables. When we get to the end of the block of code a value type is declared in, the variable goes out of scope, which is to say, it can no longer be accessed. When a reference type goes out of scope, the object it refers to may still exist provided some other reference variable refers to it. For example, here is a short piece of program code that manipulates two Integer variables: Dim X As Integer = 42 X 42 Dim Y As Integer Y 0 Y = X Console.WriteLine(X) Console.WriteLine(Y) X Y Y += 10 Console.WriteLine(X) Console.WriteLine(Y) Figure 4.8: Working with two Integer variables (values) In figure 4.8, you can see that the variables X and Y are independent of each other: I can copy the value stored in X into Y, but this does not make Y in any dependent on X in subsequent code. In contrast to this, figure 4.9 shows a similar scenario, but this time using two BankAccount variables. X Y University of Paisley Page 14 of 21

15 Dim A1 As BankAccount = New BankAccount Dim A2 As BankAccount A1.AccountName = Fred Bloggs A1.Deposit(100) A1 A2 A2 = A1 Console.WriteLine(A1.Balance) Console.WriteLine(A2.Balance) Fred Bloggs 100 A2.Withdraw(50) Console.WriteLine(A1.Balance) Console.WriteLine(A2.Balance) A1 A2 Fred Bloggs 50 Figure 4.9: Working with two BankAccount variables (references) A single object is created (using the New keyword). Subsequently, the assignment A2 = A1 makes both reference variables refer to this object Distinguishing Value and Reference Types Obviously with these pronounced differences in behaviour, it is important to know when you are using a value type and when a reference type. The following are all value types, everything else is a reference type: Numeric types (Byte, Short, Integer, Long, Single, Double and Decimal) Date variables Char variables Boolean variables Structures, either built-in or defined by a programmer Enumerations You may find it odd that the String type is missing from this list, since we don t need to use the keyword New when we create a new string variable. With all of the other reference types, we use New to create a brand new instance to assign, and other assignments need to refer to already existing objects, as in the code in figure 4.9. However, Visual Basic strings are a special form of reference type. They are special in that New is not needed to create a String value; an un-initialized String variable is given the default value of Nothing. Oddly, this equates to an empty string ( ), since the result of: If "" = Nothing Then Console.WriteLine("Equal") End If is to display the word Equal. Strings are also special in that when they are manipulated in program code, they behave like value types. For example: Dim str As String = "Hello World!" University of Paisley Page 15 of 21

16 Dim strcopy As String = str Console.WriteLine("{0} - {1}", str, strcopy) strcopy = strcopy.toupper Console.WriteLine("{0} - {1}", str, strcopy) Listing 4.17: Manipulating strings reference variables? According to what we know about reference variables, the second Console.WriteLine() statement in listing 4.17 should print out the same upper case string twice. However, figure 4.10 shows that this is not the case. Figure 4.10: These strings are behaving like value types What is going on? According to Visual Basic s on-line help, type String is a class that represents an immutable series of characters. Immutable means can not be altered. What this is saying is that once we create a string object, we can not alter it by changing any part of it we can t convert it to upper case, or replace any characters in it or any other piecemeal manipulation. If we change a string in code, the whole string gets replaced! Look back to listing 4.17 again and we can now see what is going on: 1. str is declared and initialized with Hello World!. Hello World! is the string object and str is made to reference it. 2. strcopy is declared, and made to refer to the object that str references 3. Both reference variables are written out, and so the same object is displayed twice. strcopy is made to reference the string object that is an upper case version of the string it currently references. Since a string is immutable, the only way VB can manage this is to create a new string object, and initialize it to the upper case value 4. Both reference variables are written out, this time each referring to a different string object. str strcopy str Hello World! Hello World! strcopy Figure 4.11: Manipulating immutable strings HELLO WORLD! We can take from this that Strings are different in.net. See the set text for a fuller explanation why this is so. University of Paisley Page 16 of 21

17 1.3 Review Questions 1. Where must code be placed if it is to be able to access a Private member variable of a class? 2. What is the difference between a Sub and a Function? 3. How is a Property different from a Sub or a Function? 4. How do you create a Read-Only property? 5. What is a constructor? 6. How does a Constructor differ from a normal Sub? 7. What is wrong with using these two overloaded constructor definitions in the same class?: Public Sub New(CustomerName As String) Code omitted Public Sub New(Customer As String) Code omitted 8. How does an event differ from a Sub? 9. What change is needed to the declaration of an object reference variable if the object must be able to respond to events? 10. How does a reference type variable differ from a value type variable? University of Paisley Page 17 of 21

18 1.4 Solutions to Exercises Exercise 4.1 Public Class BankAccount Public AccountName As String Public AccountNumber As Long Private Balance As Integer Private PIN As Short 'Other code here... End Class Note that several types could have been used here. A Long integer variable gives a big enough range to cover a bank account number (an Integer, at approx 10 digits long may not). Defining the PIN as a Short integer would do since most bank machines expect a 4 digit PIN. However, it could be more efficient to have PIN as an array of 4 Chars ( Private PIN(3) As Char). Exercise 4.2 Class Person Public Name As String Public As String Public DateOfBirth As Date Public Function Age() As Integer Return DateDiff(DateInterval.Year, DateOfBirth, _ End Function End Class Date) Public Dim P As Person = New Person P.Name = Fred Bloggs P. = fred@bloggo.com P.DateOfBirth = 22/10/1975 Console.WriteLine(P.Age) Note the above statements should be placed in a code module to test them. Create a Console application, and enter the code entirely within the pre-defined module (adding the code in to the existing empty definition of Sub Main.) Exercise 4.3 Class Person Public FirstName As String Public LastName As String Public As String Public DateOfBirth As Date Public Function Age() As Integer Return DateDiff(DateInterval.Year, DateOfBirth, _ End Function Public Property FullName() As String Get Date) University of Paisley Page 18 of 21

19 Return FirstName & & LastName End Get End Property End Class Public Dim P As Person = New Person P.FirstName = Fred P.LastName = Bloggs P. = fred@bloggo.com P.DateOfBirth = 22/10/1975 Console.WriteLine(P.FullName) Console.WriteLine(P.Age) Exercise 4.3 Class Person Public FirstName As String Public LastName As String Public As String Public DateOfBirth As Date Public Sub New(ByVal FName As String, _ ByVal LName As String, _ ByVal em As String, ByVal DOB As Date) FirstName = FName LastName = LName = em DateOfBirth = DOB Public Function Age() As Integer Return DateDiff(DateInterval.Year, DateOfBirth, _ Date) End Function Public Property FullName() As String Get Return FirstName & & LastName End Get End Property End Class Public Dim P As Person = New Person( Fred, Bloggs, _ Exercise 4.5 As before... fred@bloggo.com, 12/10/1975 ) Simply delete New from the previous solution and run the program. Exercise A4.1 Add this code within the class Public Property Operator() As Char Get University of Paisley Page 19 of 21

20 End Get Return mvaroperator Set(ByVal Value As Char) End Set End Property mvaroperator = Value Exercise A4.2 Amend the result method to include the division operator as shown below: Public Function Result() As Decimal If Operator = "+" Then End If Return Number1 + Number2 If Operator = "-" Then End If Return Number1 - Number2 If Operator = "*" Then End If Return Number1 * Number2 If Operator = "/" Then End If If Number2 <> 0 Then Else End If Return Number1 / Number2 Dim Ex As New _ Throw Ex Exception("Can not divide by zero.") Note added a Power function... If Operator = "^" Then End If End Function Return Number1 ^ Number2 University of Paisley Page 20 of 21

21 1.5 Answers to Review Questions 1. Where must code be placed if it is to be able to access a Private member variable of a class? Within the class definition i.e. in a Sub, Function or Property definition inside the class code. 2. What is the difference between a Sub and a Function? A Function does some work and then returns a value to the calling statement. A Sub does not return a value. 3. How is a Property different from a Sub or a Function? A Property is defined so that a call to it appears as if it is accessing a member variable. Properties are defined as two optional parts one part (the Get) defines how the property returns information from the object s member variables as a value, the other part (the Set) defines how object ember variables are updated when the property is assigned a value. 4. How do you create a Read-Only property? Delete the Set part of the definition. 5. What is a constructor? A Sub that is defined to be called as an object is created, so that the object s member variables can be put into a well defined state. 6. How does a Constructor differ from a normal Sub? A constructor can only be defined for a class, and can be called within a declaration statement. 7. What is wrong with using these two overloaded constructor definitions in the same class?: Public Sub New(CustomerName As String) Code omitted Public Sub New(Customer As String) Code omitted Both overloaded Subs have the same signature, so the compiler could not distinguish between them (and will reject the second definition) 8. How does an event differ from a Sub? An event is a signal sent from within an object, and contains no executable code. An event-handler is a Sub that is used to define the response to an event. 9. What change is needed to the declaration of an object reference variable if the object must be able to respond to events? The variable should be declared using the WithEvents keyword. 10. How does a reference type variable differ from a value type variable? A value type variable holds a value directly, while a reference type variable provides access to objects that may hold values. Because of this, assigning a value type to another variable creates a copy, while assigning a reference type to another variable creates a second reference to the same object. University of Paisley Page 21 of 21

Storing Data in Objects

Storing Data in Objects Storing Data in Objects Rob Miles Department of Computer Science 28d 08120 Programming 2 Objects and Items I have said for some time that you use objects to represent things in your problem Objects equate

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 2 Building Multitier Programs with Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Objectives Discuss object-oriented terminology Create your own class and instantiate

More information

C# Programming for Developers Course Labs Contents

C# Programming for Developers Course Labs Contents C# Programming for Developers Course Labs Contents C# Programming for Developers...1 Course Labs Contents...1 Introduction to C#...3 Aims...3 Your First C# Program...3 C# The Basics...5 The Aims...5 Declaring

More information

VARIABLES AND TYPES CITS1001

VARIABLES AND TYPES CITS1001 VARIABLES AND TYPES CITS1001 Scope of this lecture Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Primitive types Every piece of data

More information

Module 6: Fundamentals of Object- Oriented Programming

Module 6: Fundamentals of Object- Oriented Programming Module 6: Fundamentals of Object- Oriented Programming Table of Contents Module Overview 6-1 Lesson 1: Introduction to Object-Oriented Programming 6-2 Lesson 2: Defining a Class 6-10 Lesson 3: Creating

More information

CS112 Lecture: Defining Instantiable Classes

CS112 Lecture: Defining Instantiable Classes CS112 Lecture: Defining Instantiable Classes Last revised 2/3/05 Objectives: 1. To describe the process of defining an instantiable class 2. To discuss public and private visibility modifiers. Materials:

More information

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction 1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)

More information

Industrial Programming

Industrial Programming Industrial Programming Lecture 4: C# Objects & Classes Industrial Programming 1 What is an Object Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a

More information

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes What is an Object Industrial Programming Lecture 4: C# Objects & Classes Central to the object-oriented programming paradigm is the notion of an object. Objects are the nouns a person called John Objects

More information

7. Inheritance & Polymorphism. Not reinventing the wheel

7. Inheritance & Polymorphism. Not reinventing the wheel 7. Inheritance & Polymorphism Not reinventing the wheel Overview Code Inheritance Encapsulation control Abstract Classes Shared Members Interface Inheritance Strongly Typed Data Structures Polymorphism

More information

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES

Introduction. In this preliminary chapter, we introduce a couple of topics we ll be using DEVELOPING CLASSES Introduction In this preliminary chapter, we introduce a couple of topics we ll be using throughout the book. First, we discuss how to use classes and object-oriented programming (OOP) to aid in the development

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Procedures in Visual Basic

Procedures in Visual Basic Procedures in Visual Basic https://msdn.microsoft.com/en-us/library/y6yz79c3(d=printer).aspx 1 of 3 02.09.2016 18:50 Procedures in Visual Basic Visual Studio 2015 A procedure is a block of Visual Basic

More information

Object Oriented Programming with Visual Basic.Net

Object Oriented Programming with Visual Basic.Net Object Oriented Programming with Visual Basic.Net By: Dr. Hossein Hakimzadeh Computer Science and Informatics IU South Bend (c) Copyright 2007 to 2015 H. Hakimzadeh 1 What do we need to learn in order

More information

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class CS112 Lecture: Defining Classes Last revised 2/3/06 Objectives: 1. To describe the process of defining an instantiable class Materials: 1. BlueJ SavingsAccount example project 2. Handout of code for SavingsAccount

More information

Object-Oriented Programming Paradigm

Object-Oriented Programming Paradigm Object-Oriented Programming Paradigm Sample Courseware Object-Oriented Programming Paradigm Object-oriented programming approach allows programmers to write computer programs by representing elements of

More information

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

More information

Visual Basic 2008 Anne Boehm

Visual Basic 2008 Anne Boehm TRAINING & REFERENCE murach s Visual Basic 2008 Anne Boehm (Chapter 3) Thanks for downloading this chapter from Murach s Visual Basic 2008. We hope it will show you how easy it is to learn from any Murach

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

CS112 Lecture: Primitive Types, Operators, Strings

CS112 Lecture: Primitive Types, Operators, Strings CS112 Lecture: Primitive Types, Operators, Strings Last revised 1/24/06 Objectives: 1. To explain the fundamental distinction between primitive types and reference types, and to introduce the Java primitive

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Mobile App:IT. Methods & Classes

Mobile App:IT. Methods & Classes Mobile App:IT Methods & Classes WHAT IS A METHOD? - A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. -

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Last lecture. Lecture 9. in a nutshell. in a nutshell 2. Example of encapsulation. Example of encapsulation. Class test. Procedural Programming

Last lecture. Lecture 9. in a nutshell. in a nutshell 2. Example of encapsulation. Example of encapsulation. Class test. Procedural Programming 1 Lecture 9 Last lecture Class test Has been marked Collect your marks at your next seminar Seminars There are seminars this week to go through the class test Meet in the classroom indicated on the timetable

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.

More information

DEVELOPING OBJECT ORIENTED APPLICATIONS

DEVELOPING OBJECT ORIENTED APPLICATIONS DEVELOPING OBJECT ORIENTED APPLICATIONS By now, everybody should be comfortable using form controls, their properties, along with methods and events of the form class. In this unit, we discuss creating

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Lecture 10 OOP and VB.Net

Lecture 10 OOP and VB.Net Lecture 10 OOP and VB.Net Pillars of OOP Objects and Classes Encapsulation Inheritance Polymorphism Abstraction Classes A class is a template for an object. An object will have attributes and properties.

More information

CPS122 Lecture: Defining a Class

CPS122 Lecture: Defining a Class Objectives: CPS122 Lecture: Defining a Class last revised January 14, 2016 1. To introduce structure of a Java class 2. To introduce the different kinds of Java variables (instance, class, parameter, local)

More information

CS 1302 Chapter 9 (Review) Object & Classes

CS 1302 Chapter 9 (Review) Object & Classes CS 1302 Chapter 9 (Review) Object & Classes Reference Sections 9.2-9.5, 9.7-9.14 9.2 Defining Classes for Objects 1. A class is a blueprint (or template) for creating objects. A class defines the state

More information

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals VARIABLES WHAT IS A VARIABLE? A variable is a storage location in the computer s memory, used for holding information while the program is running. The information that is stored in a variable may change,

More information

HST 952. Computing for Biomedical Scientists Lecture 5

HST 952. Computing for Biomedical Scientists Lecture 5 Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 5 Outline Recursion and iteration Imperative and

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Appendix G: Writing Managed C++ Code for the.net Framework

Appendix G: Writing Managed C++ Code for the.net Framework Appendix G: Writing Managed C++ Code for the.net Framework What Is.NET?.NET is a powerful object-oriented computing platform designed by Microsoft. In addition to providing traditional software development

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Ex: If you use a program to record sales, you will want to remember data:

Ex: If you use a program to record sales, you will want to remember data: Data Variables Programs need to remember values. Ex: If you use a program to record sales, you will want to remember data: A loaf of bread was sold to Sione Latu on 14/02/19 for T$1.00. Customer Name:

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Building Multitier Programs with Classes

Building Multitier Programs with Classes 2-1 2-1 Building Multitier Programs with Classes Chapter 2 This chapter reviews object-oriented programming concepts and techniques for breaking programs into multiple tiers with multiple classes. Objectives

More information

Defining Your Own Functions/Methods

Defining Your Own Functions/Methods Chapter 4 Defining Your Own Functions/Methods What is in This Chapter? Object-Oriented Programming (OOP) involves creating objects of our own. In this set of notes, we will discuss how to write functions

More information

Microsoft Visual Basic 2005: Reloaded

Microsoft Visual Basic 2005: Reloaded Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 10 Creating Classes and Objects Objectives After studying this chapter, you should be able to: Define a class Instantiate an object from a class

More information

Functional Programming, Classes, and Recursion!

Functional Programming, Classes, and Recursion! CS 1301 Homework 9 Functional Programming, Classes, and Recursion! Due: Monday, April 20 th before 11:55 pm THIS IS AN INDIVIDUAL ASSIGNMENT! Students are expected to abide by the Georgia Tech Honor Code.

More information

Design Patterns: State, Bridge, Visitor

Design Patterns: State, Bridge, Visitor Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

MODELS OF DISTRIBUTED SYSTEMS

MODELS OF DISTRIBUTED SYSTEMS Distributed Systems Fö 2/3-1 Distributed Systems Fö 2/3-2 MODELS OF DISTRIBUTED SYSTEMS Basic Elements 1. Architectural Models 2. Interaction Models Resources in a distributed system are shared between

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Creating and Using Objects

Creating and Using Objects Creating and Using Objects 1 Fill in the blanks Object behaviour is described by, and object state is described by. Fill in the blanks Object behaviour is described by methods, and object state is described

More information

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. Chapter 12 OOP: Creating Object- Oriented Programs McGraw-Hill Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. Objectives (1 of 2) Use object-oriented terminology correctly. Create

More information

CS608 Lecture Notes. Visual Basic.NET Programming. Object-Oriented Programming Inheritance (Part II) (Part II of II) (Lecture Notes 3B)

CS608 Lecture Notes. Visual Basic.NET Programming. Object-Oriented Programming Inheritance (Part II) (Part II of II) (Lecture Notes 3B) CS608 Lecture Notes Visual Basic.NET Programming Object-Oriented Programming Inheritance (Part II) (Part II of II) (Lecture Notes 3B) Prof. Abel Angel Rodriguez CHAPTER 8 INHERITANCE...3 8.2 Inheritance

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Level 3 Computing Year 2 Lecturer: Phil Smith

Level 3 Computing Year 2 Lecturer: Phil Smith Level 3 Computing Year 2 Lecturer: Phil Smith Previously We started to build a GUI program using visual studio 2010 and vb.net. We have a form designed. We have started to write the code to provided the

More information

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer?

Midterm 2. 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer? Midterm 2 7] Explain in your own words the concept of a handle class and how it s implemented in C++: What s wrong with this answer? A handle class is a pointer vith no visible type. What s wrong with

More information

HOUR 4 Understanding Events

HOUR 4 Understanding Events HOUR 4 Understanding Events It s fairly easy to produce an attractive interface for an application using Visual Basic.NET s integrated design tools. You can create beautiful forms that have buttons to

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

Microsoft Visual Basic 2015: Reloaded

Microsoft Visual Basic 2015: Reloaded Microsoft Visual Basic 2015: Reloaded Sixth Edition Chapter Three Memory Locations and Calculations Objectives After studying this chapter, you should be able to: Declare variables and named constants

More information

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java.

DC69 C# &.NET JUNE C# is a simple, modern, object oriented language derived from C++ and Java. Q.2 a. What is C#? Discuss its features in brief. 1. C# is a simple, modern, object oriented language derived from C++ and Java. 2. It aims to combine the high productivity of Visual Basic and the raw

More information

d2vbaref.doc Page 1 of 22 05/11/02 14:21

d2vbaref.doc Page 1 of 22 05/11/02 14:21 Database Design 2 1. VBA or Macros?... 2 1.1 Advantages of VBA:... 2 1.2 When to use macros... 3 1.3 From here...... 3 2. A simple event procedure... 4 2.1 The code explained... 4 2.2 How does the error

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

Agenda: Notes on Chapter 3. Create a class with constructors and methods. Bell Work 9/19/16: How would you call the default constructor for a class called BankAccount? Agenda: Notes on Chapter 3. Create a class with constructors and methods. Objectives: To become familiar with

More information

Public Class ClassName (naming: CPoint)

Public Class ClassName (naming: CPoint) Lecture 6 Object Orientation Class Implementation Concepts: Encapsulation Inheritance Polymorphism Template/Syntax: Public Class ClassName (naming: CPoint) End Class Elements of the class: Data 1. Internal

More information

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1 OBJECT ORIENTED SIMULATION LANGUAGE OOSimL Reference Manual - Part 1 Technical Report TR-CSIS-OOPsimL-1 José M. Garrido Department of Computer Science Updated November 2014 College of Computing and Software

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

C# Language. CSE 409 Advanced Internet Technology

C# Language. CSE 409 Advanced Internet Technology C# Language Today You will learn Building a basic class Value Types and Reference Types Understanding Namespaces and Assemblies Advanced Class Programming CSE 409 Advanced Internet Technology Building

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

variables programming statements

variables programming statements 1 VB PROGRAMMERS GUIDE LESSON 1 File: VbGuideL1.doc Date Started: May 24, 2002 Last Update: Dec 27, 2002 ISBN: 0-9730824-9-6 Version: 0.0 INTRODUCTION TO VB PROGRAMMING VB stands for Visual Basic. Visual

More information

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction to Computers and Programming Languages CS 180 Sunil Prabhakar Department of Computer Science Purdue University 1 Objectives This week we will study: The notion of hardware and software Programming

More information

Java Classes and Objects

Java Classes and Objects Table of contents 1 Introduction Case Study - Stack 2 3 Integer String Case Study - Stack Introduction Case Study - Stack Classes Template for creating objects Definition of State (What it knows) Definition

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations , 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials

More information

IT150/IT152 Concepts Summary Sheet

IT150/IT152 Concepts Summary Sheet (Examples within this study guide/summary sheet are given in C#.) Variables All data in a computer program, whether calculated during runtime or entered by the user, must be stored somewhere in the memory

More information

CSC 220: Computer Organization Unit 10 Arithmetic-logic units

CSC 220: Computer Organization Unit 10 Arithmetic-logic units College of Computer and Information Sciences Department of Computer Science CSC 220: Computer Organization Unit 10 Arithmetic-logic units 1 Remember: 2 Arithmetic-logic units An arithmetic-logic unit,

More information

CPS122 Lecture: Introduction to Java

CPS122 Lecture: Introduction to Java CPS122 Lecture: Introduction to Java last revised 10/5/10 Objectives: 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3. To introduce

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

Chapter 6 Classes and Objects

Chapter 6 Classes and Objects Chapter 6 Classes and Objects Hello! Today we will focus on creating classes and objects. Now that our practice problems will tend to generate multiple files, I strongly suggest you create a folder for

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

MODELS OF DISTRIBUTED SYSTEMS

MODELS OF DISTRIBUTED SYSTEMS Distributed Systems Fö 2/3-1 Distributed Systems Fö 2/3-2 MODELS OF DISTRIBUTED SYSTEMS Basic Elements 1. Architectural Models 2. Interaction Models Resources in a distributed system are shared between

More information