19
Chapter 9: Getting Comfortable with Object-Oriented Programming

Chapter 9: Getting Comfortable with Object- Oriented Programming

Embed Size (px)

Citation preview

Page 1: Chapter 9: Getting Comfortable with Object- Oriented Programming

Chapter 9:Getting Comfortable with Object-Oriented Programming

Page 2: Chapter 9: Getting Comfortable with Object- Oriented Programming

Introduction• In this chapter, you will learn about Visual Basic object-

oriented programming:▫ This will include learning about a number of new

programming concepts. Abstraction Encapsulation Inheritance Polymorphism

▫ You will also learn more about working with objects Examples of objects provided by VB and the .NET Framework How to create your own objects by creating custom classes

▫ How to store and protect the data stored in your custom objects and to provide access to it through the implementation of properties and methods.

• Specifically we will learn:▫ About object-oriented programming concepts and terms▫ How to define custom classes▫ How to instantiate objects based on your custom classes▫ How to set up method overloading within custom classes▫ How to provide controlled access to the data stored within objects

Page 3: Chapter 9: Getting Comfortable with Object- Oriented Programming

Object-Oriented Programming• OOP is a major feature of Visual Basic. In OOP, data and code are

grouped together as objects. ▫ Objects are self-contained entities.▫ For example:

the forms and controls each represent a different type of object▫ Objects can store data and provide a carefully designed interface for

accessing their data and exercising their functionality. This access is provided through object propertiesproperties and methodsmethods

▫ Objects have the ability to validate any data that is passed to them and to reject it if it fails to meet certain predefined criteria. Properly defined objects make applications more reliableProperly defined objects make applications more reliable

• Because objects control access to themselves and to their data, you can think of them as being like a black box. This means that you may know what a given object does and to use it. But in fact you don’t really know how it was put together or what makes it work.▫ For examplee:

Think about the Form object. DO YOU KNOW HOW THEY WORK? Visual Basic makes forms available to you as classes. Forms have their own properties, such as

background color and foreground color, such as maximize and minimize, which you do not have to define.

All you know is how to add new controls to your forms in order to modify them. Forms also have events like the Load event, to which they automatically know how to respond

Page 4: Chapter 9: Getting Comfortable with Object- Oriented Programming

OOP Terms• In visual Basic, objects are created from classes. A class

provides a template that specifies data, properties, and methods that are available for working with data.

A class is a template that can be used to instantiate objects

• Visual Basic provides access to a large collection of classes. The code behind a Form comes from the Form class, which is located in the System.Windows.Forms namespace.

A namespace is an organized collection of classes. The .NET Framework provides access to numerous namespaces, which it

makes available in its class Library.▫ Examples of other classes include System.Windows.Forms.Button,

where the Button class is defined▫ System.Windows.Forms.CheckBox, where the CheckBox class is

defined.• We have been working with classes in all of the chapter game

projects throughout the book. We should have realized this due to the syntax:

Public Class Form1 End Class

Page 5: Chapter 9: Getting Comfortable with Object- Oriented Programming

OOP Terms• The first statement

Public Class Form1

• Publically defines a new Class called Form1, and the last statement

End Class

• Defines the end of the class.▫ Visual Basic makes things easy on the programmer by hiding much of

the work that is truly does behind the scenes. If you wish to see everything that is happening you can simply click on the

Show All File button in the Solution Explorer, expand the Form1.vb entry and click on the Form1.designer.VB entry.

• Now we wish to learn a littler about what is going on in this Form.▫ First look at these statements:

Partial Public Class Form1 Inherits System.Windows.Forms.Form

▫ As we can see the form that Visual Basic has automatically provided you with is actually inherited (or cloned) from the Form class stored in the System.Windows.Forms namespace

Page 6: Chapter 9: Getting Comfortable with Object- Oriented Programming

OOP Terms• OOP simplifies the coding process by hiding many of the

complexities of and application from the programmer. In addition, it promotes the reuse of code by making it possible to define a class once and then use it over and over again to create as many objects as required.

• Visual Basic also allows you to create you own custom classes, which is much of the focus of this chapter.

• Now we look at key OOP terms:▫ Abstraction, encapsulation, inheritance, and polymorphism

Abstraction: This is the process by which you define in a program code a logical

represenstation of a class. This includes the specification of the base functionality belonging to the class and the definitions of properties and methods that are required for the proper operation of the class.▫ Returning to the Form class as an example, base properties include the Text, Size,

BackColor, and ForeColor properties

Page 7: Chapter 9: Getting Comfortable with Object- Oriented Programming

OOP Terms• Now we look at key OOP terms:

▫ Abstraction, encapsulation, inheritance, and polymorphism Encapsulation:

Is the process whereby you package the base functionality of a class and provide access to the features of the class through a collection of properties and methods. When an object is created from a particular class, the inner workings of the object are hidden from the programmer. ▫ Again, consider the Form class. You don’t know what the code behind it looks like or

how it is written. You cannot directly access its internal code or data. You only know that to work with the form, you modify its properties, execute its methods, and provide code for its events. How the Form class was designed to make all these things work is hidden from you. Thus, encapsulation helps simply program development and hide complexity.

It also includes data protection, meaning that code can be added to process and verify the validity of any data passed to an object to ensure that it meets certain criteria

Inheritance: Is the process whereby one class is derived from another. When you define

a new class in your program code, such as when you define a new class for Visual Basic form, the class that you create inherits its features from a base class, which in the case of this example is System.Windows.Froms.Form

Page 8: Chapter 9: Getting Comfortable with Object- Oriented Programming

OOP Terms

Page 9: Chapter 9: Getting Comfortable with Object- Oriented Programming

Classes and Objects• A class is a template that defines all of the attributes, properties,

methods, and events required to create an object. Using abstraction, programmers develop a design for a class. Using encapsulation, they implement a class structure. One class can be established by inheriting it from another class. Finally, using overloading, programmers can extend procedures within classes to handle different sets of arguments▫ For example, you might analogize the relationship between a class and an

object as being akin to the relationship between a mold and Jell-O. The mold defines an overall form and shape of the Jell-O. Once poured into that mold and solidified, the new instance of Jell-O takes on the basic qualities of the mold. As another, more specific, example, the Form object is an instance of the Form class and has access to all the features provided by that class.

• In order to use a class, you must first instantiate it. The instantiation process varies depending on the class your are working with. ▫ For example, to instantiate a Button or CheckBox class (control), all that you

have to do is place a copy of it on a form. However, if you create your own custom class as part of a Visual Basoc application, you will create a new class instance using the New keyword.

Page 10: Chapter 9: Getting Comfortable with Object- Oriented Programming

Creating a New Class• There are a number of ways that you can create a new class.

First, as you have already seen, anytime you create a new Visual Basic application, a new class is created for you based on the System.Windows.Forms.Form class. In the case of the Dice Poker game, the new class was named frmMain.

• You can also add a new class to an application by simply inserting its declaration under the existing class definition in the code editor:

Public Class frmMain

{what ever is happening within the form}End ClassPublic Class Greeting{whatever is happening within the NEW CLASS}End Class

A data member is a variable that is defined within a class. Ordinarily, data members are hidden from the outside world and used

only within the class. However, data members can e made directly accessible from outside the class using the Public keyword.

Page 11: Chapter 9: Getting Comfortable with Object- Oriented Programming

Creating a New ClassPublic Class Form2

Private Sub Form2_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.Load

Dim SampleGreeting As New GreetingMessageBox.Show(SampleGreeting.Message)

End SubEnd ClassPublic Class Greeting

Public Message As String = “Hello World!”End Class

• The statement that you added to the Greeting class sets up a data member. Data members are by default private, meaning they cannon be accessed from outside of the class itself. ▫ However, in this example, I made the data member public just so that we

could have a working example that does something• By itself, the Greeting class does not do anything. You need to

instantiate an object based on the class in order to be able to do something. The first statement in the Form2_Load event procedure instantiates a new object named SampleGreeting using the New keyword.

• Then the MessageBox.Show method is used to access and display the SampleGreeting object’s data member.

Page 12: Chapter 9: Getting Comfortable with Object- Oriented Programming

Creating a New Class• Another way to add a new class to your application is to

create it in its own code module, separate and distinct from the form’s class code, as demonstrated in the following example.▫ Click on the Add Class option located on the Project menu.▫ Select the Class icon and type a name for the class that you

are about to define in the Name field, and then click on the Add button.

▫ A new tab will appear in the code editor, and the opening and closing class statements for the new class will be displayed.

▫ Modify the program code Type Public Message As String = “Hello World!” between the

existing class scope

Page 13: Chapter 9: Getting Comfortable with Object- Oriented Programming

Understand Data Memebers• In the previous two examples that demonstrated how to

create a new class, you learned how to define a new data member. By default, class data member are private, which means that they cannot be seen or accessed from outside the class. However, as the examples showed, you can make data member publicly available. You can also declare them as protected, in which case they can be accessed only by derived classes of the base class.▫ Although it is possible for data member to be accessed from

outside the class, they are not properties of the class. However, when made publicly available, you lose the ability to restrict control over data members. Instead of making data member public and set up properties to provide controlled access to any data stored in your classes.

Page 14: Chapter 9: Getting Comfortable with Object- Oriented Programming

Defining Class Properties• Properties can be used to set and retrieve values. To set up a

property within a class, you start declaring a private data member and then define a public procedure that provides controlled access to the value stored in the data member. The following types of property procedures are supported by Visual Basic.

• Get: Retrieves the value assigned to a property• Set: Assigns a value to the property

Public Class GreetingPrivate Message As StringPublic Property Text() As String

GetReturn Message

End GetSet (ByVal Value as String)

Message = ValueEnd set

End propertyEnd Class

▫ Before you can use an object, you must instantiate it. You can then reference its properties by specifying the name of the object, followed by a period and the name of a particular property. When you assign a value to the Text property, the Set property procedure block executes. Note that the Set property procedure is automatically passed an argument named Value in which the data passed to the Set property procedure is stored. All you have to do to finish up the property assignment is to assign the data stored in Value to a private data member (Message).

Page 15: Chapter 9: Getting Comfortable with Object- Oriented Programming

Defining Class Properties• The following statements demonstrate how to derive an object

from the Greeting class and then set and retrieve the object’s Text property. The first statement shown below instantiates a new object named SampleGreeting that is derived from the Greeting class. The next two statements assign a value to the objects Text property and then use the MessageBox.Show method to demonstrate that the property assignment was successful.

Dim objSample As New Greeting objSample.Text = “Good Morning” MessageBox.Show(objSample.Text)

▫ The advantage of setting up properties, compared to simply making data members public, is that you can add code to your property procedure to perform data validation before allowing access to the data associated with a particular property. For example;

Using an if statement can limit access to the value

Page 16: Chapter 9: Getting Comfortable with Object- Oriented Programming

Adding Class Methods• In addition to defining data members and properties in your

custom classes, you can add your own methods. To add a method to a class, all you have to do is add a Sub or Function procedure.

• REFER TO BOOK FOR THE CODE BEING DISCUSSED▫ The Greeting class has been modified by the addition of a

method named PostWelcome(). When executed, the method uses the MessageBox.Show method to

display a text message. Like all of the other object methods that you have worked with, you can call on this method by specifying the name of its object followed by a period and the name of the method.

▫ One of Visual Basic’s OOP features is polymorphism. Polymorphism is implemented in Visual Basic by providing the ability to overload class methods.

▫ When you overload a method Visual Basic makes sure that the correct method is executed based on the argument list that is passed in.

Notice that the keyword OVERLOADS is used within a Sub procedure during its definition. ▫ NOTE: For overloading to work, you must provide each overloaded procedure with a

unique set of arguments. You can vary the argument list by changing the number of arguments that are passed or by changing the types of argument passed, or a combination of both.

Page 17: Chapter 9: Getting Comfortable with Object- Oriented Programming

Inheriting from Another Class• Anytime Visual Basic provides you with a new form, behind the

scenes the new instance of the form is created by specifying the Inherits keyword and the name of the class to is to be inherited from.▫ The derived class inherits its features from the base class. Anytime you

add a control to a form, Visual Basic automatically handles the setup of the new instance of the control (object). In addition to inheriting from classes provided to you by Visual Basic and the .NET Framwork, you can derive new classes from classes that you create. For Example:

Public Class GreetingTwo

Inherits Greeting

Private Warning As String = “Action not allowed.”

Public ReadOnly Property ErrMsg() As String

Get

Return Warning

End Get

End Property

End Class

▫ You’ll notice that the GreetingTwo class not only inherits all of the proplerties and methods belonging to the Greetings class, but also extends this functionality by adding a new property of its own. In addition, you’ll notice that the new ErrMsg property has been made read-only, meaning that it can be retrieved but not modified by calling statements.

Page 18: Chapter 9: Getting Comfortable with Object- Oriented Programming

Lab 9: Rock Paper Scissors•100 pts

▫Cannot be downloaded from the books websites Any instance where I think this has happened a 0%

will result. Every class used Should be represented in the Tab

bar. This means no class should be defined under the From Class

Worth 75% Adding own comments/programming logic/ user

interface = 10% Each Successfully completed challenge = 5% each

Page 19: Chapter 9: Getting Comfortable with Object- Oriented Programming

Summary• In this chapter, you learned about Visual Basic classes and

namespaces. You learned how to create your own custom classes. You then learned how to instantiate new objects using your custume classes. The custom objects that you created included their own properties and methods. You also learned how to overload object methods and how to provide controlled access to data stored within your objects.