Computer Science
Ronald P. Kessler
Introduction to Object–Oriented
Programming (OOP)
Good morning Mr. Phelps.
Microsoft and other major corporations have endorsed a new programming scheme
know as OOP. We need to know more about this. The challenge for you and your
team will be to decipher and demystify the components of OOP. What is a class,
inheritance, polymorphism and shadowing? These sound sinister and could prove
to be a threat to our way of programming as we know it. As usual, should you or
your IT staff be discovered, we will deny any knowledge or understanding of
OOP. Which, in this case would be the truth!
My initial exposure to OOP
left me feeling overwhelmed and stressed out. I felt like Microsoft had ruined
VB6 and created this new .Net creature. I tried to make a messagebox show up in
VB.Net 2002 and couldn’t figure it out. I really felt like my programming
career was over. But after several months of denial and avoidance, I decided to
try it again. With the help of my good friend, Tony Lee, we slowly fumbled our
way through the new programming model. Now, I love this .Net stuff and wouldn’t
go back. As you study and struggle and become frustrated, please do not do what
I did. Don’t give up. If you discover that you like programming, you will
succeed and you will feel a great sense of satisfaction when you see others
using your creations. Trust me, it is not impossible!
This document is my
attempt to explain and summarize the features and philosophy surrounding
object-oriented programming. I have never found a complete summary in one place
that explained these strange sounding terms. Consequently, I have searched
around and compiled a table of this information for you.
I want you to try and keep
a couple of things in mind as you read this. One of the major benefits of the OOP
model is that it allows developers to create new products and bring them to
market faster than ever. To accomplish this, Microsoft created RAD (Rapid
application development) tools like Visual Studio. These software development
applications contain the tools we need to build sophisticated Windows and web
programs. The idea of OOP is simple. Programs should be created that can be
easily expanded for future needs and features (extensible). Programs should be written for easy maintenance &
modification and easily transportable to other projects (inheritance & polymorphism). Code should be self-contained or encapsulated so we can use it again in
new projects (code reusability). Since
the code we write will be placed into discrete sections (classes, sub routines,
and functions), several people can be working on different parts of the project
simultaneously. OOP lends itself to a team approach. If you were developing a
new game program, you would have some people working just on the artwork and
interface while another group would be actually writing the code.
Classes contain the
programming code, any data, properties, methods & events we create and are
saved in their own disk file. Think of how we use a Windows form. It is a class
based upon the original form class created by MS. We simply add the form
specifications from the .Net library to our project. Then, we have access to all the capabilities
of our new form object. Then we can add to it and customize it to suit our
needs. The point is, we do not have to create a new control (form, buttons,
etc.) from scratch every time we need one. We start off with a sort of template
and go from there. That is what inheritance is all about. OOP gives us the
ability to use one class in order to create a brand new class that is a clone
of the original. In this way, we can make it do anything we need it too without
messing up the original!
You add a Class to your
projects from Solution Explorer. Once your class is completed, you can use it
to bring your new creation to life. This process is called instantiation. When you instantiate an object, it means you create
it for use. Then we say you have an instance of that object running. Picture
this. When you start MS Word and then launch another copy of Word, you have two
instances of Word running on the computer inside their own process. Each
process is managed by the O/S. Well, in
Visual Studio, each program, its objects, properties & methods are all
managed by the common language runtime program (CLR). The CLR in turn,
communicates with the O/S to run our application. The CLR is responsible for
routing O/S events to our application. When the user pushes a key, Windows
alerts the CLR and it directs that action to the Keypress event in our
application where we handle it, for instance.
I really like a cool
feature of OOP called “reusability”. By breaking programs into self-contained
parts, it allows programmers to easily change things without having to spend
time searching around to find where a particular piece of code is. If I create
a class called “Customer” and it has all the properties and methods to handle
customer information, I will be able to work on that class alone when I make
changes. I do not have to disturb the class called “GetData” or “SearchDatabase”,
for example. You see, all the functionality and features are self-contained
inside their own classes. This is called “encapsulation”. This also makes it
easier to create a new product in the future as well. If I want to create a new
game based on the previous version, I can add the pieces and parts I need from
the old one and add it to my new project without having to start from scratch.
Inheritance
I would like you to
imagine yourself wearing two hats. One hat your wear is that of a developer and
the other one as a programmer. What I mean is this. As a developer, you are
creating classes that programmers are going to use to make things. Microsoft is
a developer of tools and classes like the ones in the .Net framework. We, as
programmers use those tools and built-in classes so we can make programs for
our own customers. Keep this model in mind as you read this section.
As a developer, you have
control over what a programmer can do with your class. You can create it in
such a way so the class can be “cloned” and modified. Microsoft did this for
most of the .Net classes. They have allowed us to create new controls from
their controls. If they didn’t design them that way, then we would not be able
to accomplish yet another aspect of OOP called “extensibility”. This is a big
word that simply means that classes and objects should be designed to handle
future needs and expanded capabilities. If I create a class that reads a
database but I limit it to only 1500 records, my class is not extensible. But
if I create a property to let the programmer decide how many records to access,
it is more extensible.
The ability to create new
classes from a parent or base class is called inheritance. Just like you and I inherit DNA from our parents, OOP
allows us to create new classes from existing ones. While you and I are not
clones, we do have similar traits as other family members. In the case of
computer programming, we can create
clones of existing objects and then modify them as we need to. That way we do
not have to start from scratch (remember RAD?). Look at how easy it is to
create a new textbox called RKTextBox from the textbox control that comes with
VS. In VB we use the Inherits
keyword.
Public Class RKTextBox
Inherits System.Windows.Forms.TextBox
End Class
One of the cool things
about inheritance is that we can take the child class (sometimes called
subclass or derived class) and add our own features to it or substitute our
properties/methods for the identically-named ones in the parent or base class. Remember,
the child is a clone of the parent. So it has the identical properties &
methods as the original. That means the new class has the same property names
too. That’s right. I can create a new textbox control and change the way the “text”
property works in my new control while maintaining the name “text”. This
expands your options. You can decide to use the Keypress event from your base
class or the KeyPress event from the child class! This gives programmers
unprecedented control over the objects we create. You can decide what people
can do with your new class. Then, you can decide what they can do with the members of that class (the properties,
methods, & events). For instance, you can decide whether to allow or
disallow a programmer from inheriting your class at all. If you decide to not
let someone inherit your class, we say your class is “sealed” and no one can
modify it or add more features to it. I suppose if you had a patented procedure
or high security process that you needed to keep it a secret, it would make
sense to do that.
In VB, you use the keyword
Inheritable or NotInheritable when you create your class. You can also use the
keywords Overridable or NotOverridable when you create Subs or
Functions inside your class. These commands will either (1) let a programmer
create a new method with the same name as your original, or (2) not allow the
method to be overridden. Remember, the Subs & Functions we create in a
class are viewed as methods to the programmer using our classes (even if the
programmer is us!).
In VB we would block
inheritance of our class like this:
NotInheritable Class ComputeTax
TotalTax = x * .08
End Class
Polymorphism
Finally, there is the
concept of polymorphism. Here is yet another big word that just means that two
different objects in different forms can be treated as the same. Polymorphism
is responsible for how inheritance works. In fact, I guess we should think of
it as an attribute of inheritance and not a separate thing. Remember what I
said before, if I create a new class that inherits all of its attributes from
another class my new child class is like a clone. If the parent class had a
text property, so does my new one and it will work the same way.
Furthermore, inheritance
& polymorphism allow us to substitute a method from our child class for the
one of the same name in the parent class. In other words, the text property in
my child class can be used instead of the text property in the parent. This
lets me add/change the capabilities of a method but still use the same name.
This allows me to “substitute” my new method for the old one. But, I can still
use the original if I need to. In VB I would use MyBase.Text to access the text
property of the base or parent class. If all this sounds confusing, don’t feel
alone. Until you actually play with this stuff for a while, it is hard to
digest.
Polymorphism allows us to
do something else that is quite useful. Think of the MessageBox.Show function
that comes with VS for a second. You know that there are numerous ways to call
or use MessageBox. Look at these examples:
MessageBox.Show("Welcome to my store")
MessageBox.Show("Welcome to my store", "Ron's Store")
MessageBox.Show("Welcome to my store", "Ron's Store", MessageBoxButtons.OK,
MessageBoxIcon.Information)
I want you to notice the
different ways I called the Show method. I used a different list of parameters
each time. But also notice that I did not have to call three different
messagebox’s. In other words, MS wrote this so I could use the same name object
& method (MessageBox.Show) but they made it accept different arguments to
fit my needs. This is called Overloading.
You will find it very useful when you want to allow yourself or other
programmers to do this same thing with the methods you create! When I looked at
MessageBox in the Object Browser inside VS, I discovered that there are 21
different ways to call the Show method!
Constructors
I want to talk about
something else that will hopefully show you how overloading can be of benefit
to you. When you run your application in VS, the class definitions for the
objects (forms, controls, etc) are compiled into something called an assembly. The
assembly is MSIL code, not machine code. This .EXE file is the code executed by
the CLR & O/S. By the way, when you hear someone talk about “managed code”
I want you to know that they are referring to an assembly that is managed by
the CLR. Anyway, when an object is being created, VB runs a special Sub called
“New”. In most VB programs we don’t create this sub so it is created for us.
However, I am going to show you a reason for doing it yourself.
The Sub called “New” is
called a constructor. I guess they call it that because this sub runs just
after your object is created and before it becomes visible (like a form or
control) or before it can be used. It is a place for you to put in some code to
initialize the object. In previous versions of VB, there was a sub called
“initialize”. They got rid of it and we now use this constructor in the same
way. Now, keep Messagebox in mind as I describe something to you.
Let’s say I create a new
class called “ReadAFile”. Just like MS did with Messagebox, I decide to let my
programmers have options when they use my class. They can just call the class,
they can call it and pass the name of the file to open, or they can pass the
name of the file and the filemode (read, write, append). If they don’t’ pass in
all the parameters, I assign default values for them.
In order to let someone
have this flexibility with any class, you create multiple subs all with the
same name of New. Yes, you can have multiple
sub routines in a class with the same name. This process is called overloading. Look below at my code. The
first constructor takes no arguments but the second one takes a string to hold
the filename they want to open. The third constructor takes two arguments. These
different constructor subs just give programmers options for how they
instantiate my class.
Public Class ReadAFile
Private m_FileName
As String
Private m_FileMode
As String
Sub New()
'This
constructor is used when they do not pass parameters when the class
'is
instantiated.
End Sub
Sub New(ByVal NameOfFile As String)
'---this
constructor is used if they pass the name of the file
m_FileName = NameOfFile
End Sub
Sub New(ByVal NameOfFile As String, ByVal FileMode As String)
'---this
constructor is used if they pass the file name & the filemode
m_FileName = NameOfFile
m_FileMode = FileMode
End Sub
End Class
Notice I have three Subs
called “New”. Each is a constructor with a unique signature. A signature refers
to the arguments the Sub or Function takes. Each Sub is seen as a separate
routine by the compiler because each has a different set of arguments. An
argument is simply the list of things you can pass into the Sub and in the case
of a function, the type of object that is returned by that function. How does
VB know which one to use? Well, the compiler has been designed to use the one
where the signature of the Sub or Function matches the one “Dimmed” by the programmer.
When programmers want to use my
class, they have three options because I created three overloaded constructors!
Dim
MyFileReader As New
ReadAFile()
Dim
MyFileReader As New
ReadAFile(FileName)
Dim
MyFileReader As New
ReadAFile(FileName, FileMode)
So the next time you use
the “new” keyword, try to imagine how VB runs the code that creates your object.
After creating the object from a class, VB looks inside the constructor(s) to
see if there is anything it should do to set initial values. When the object is
Dimmed the compiler will match the Dim statement and the
parameter list with those in the constructors. If there is a match the object
is created. If there is not any constructor that matches the argument list,
then you get a compiler error and the program will not run.
More Options with Inheritance
As you have come to expect
with all this .Net stuff, there are many ways to do the same task. Well, all
this inheritance stuff is no exception. Try to remember this, when you use the
New keyword, an object is created. When you create an object in code, you then
have access to all the members (properties, methods, & events) associated
with that object. However, if you do not use the New keyword to Dim an object, you do not have access to all its
members (properties & methods). So what is the big deal you ask? Well, it
turns out that you can access a
method from a class without actually creating it. Just when you thought you had
this figured out, I have to mention this!
I have read several
articles on when to use the New keyword and when not to. Here is the gist of
the story….If you need access to all the properties and methods of an object
then use “New” when you dim it. If those methods need to use other methods in
your object, then use “New”. That is simple enough. But, MS (or someone)
decided to give us a chance to use a method without going to all the trouble of
creating an object. This, they figure, will save CPU cycles and some memory and
make your application run a bit faster.
In order for this to work,
the developer must create the method with the keyword “Shared”. In VB we would do this:
Public
Class MathMaker
Public Shared Function
DoMath(ByVal FirstNumber As Int16, ByVal SecondNumber As Int16) as Int16
Dim
result as Int16 = FirstNumber + SecondNumber
Return
result
End
Function
End Class
and
in C# we would use the static keyword like this:
public static bool IsPresent(txtZip)
If a function (method) is
declared as Shared it means the programmer can access it without instantiating
the object! To use it, I could do this:
Public
Class MathMaker
Public Shared Function
DoMath(ByVal FirstNumber As Int16, ByVal SecondNumber As Int16) as Int16
Dim
result as Int16 = FirstNumber + SecondNumber
Return
result
End
Function
End Class
Dim myTotal as Int16 = 0
myTotal = MathMaker.DoMath(9,14)
If DoMath was not declared
with the Shared keyword, I would have to do this:
Dim myAdder as New MathMaker
Dim myTotal as Int16 = 0
myTotal = myAdder.DoMath(9,14)
Do you see the difference?
Any property, field (private variable inside a property is called a field),
Sub, or Function that is defined with “Shared” can be accessed this way. Keep
in mind, that MS did this to make things a bit easier but these shared members
can’t access data from any non-shared member even from the same class. So here
is what I do. When I am programming stuff for myself, I often create shared
functions. That way I can simply use them without instantiating an object. It
just makes things a bit simpler sometimes. It is just another of the million
options you have when you are developing Windows applications!
I hope this article has
helped you to understand and appreciate the enormous capabilities of OOP. Think
about how you architect your applications with these constructs in mind and I
think you will end up writing much better code. At any rate, don’t lose your
sense of humor with all this. Be creative and productive. As always, this
report will self-destruct as soon as you finish reading it!
Summary of Object-Oriented
Programming Concepts
|
Item |
Purpose |
More details… |
|
Objects |
·
A Class
is a file that you create which defines all the programming, data, features
& capabilities of an object. ·
Objects simulate
real-world things in software and are created from a class definition. |
A class is the code and data that defines the
object to be instantiated (created). When a
program is compiled into MSIL, it is created inside of an assembly. This
assembly is an .EXE file for Windows apps and a .DLL for web applications.
This is the file that is executed on the client machine. |
|
Abstraction |
A limited representation of a real thing. Objects
in the computer are modeled after things we experience in life. But not every
aspect of a real-world thing is created. |
Only the members (Properties/Methods/Variables)
that are of use to the end user are visible. The object is like a black box.
Programmers use the members of the class to work with it. |
|
Encapsulation |
All code to make the object perform its job is
contained inside the object itself. |
I design properties/methods for programmers to
use. They don't have to know how everything works internally to use my
object. |
|
Inheritance |
OOP lets us create new classes based on another
class. My new class inherits all the capabilities of the parent or base
class. Developers decide if they will let someone
customize their class. If I do not want someone to modify or extend my class,
I create it using the NotInheritable
keyword. This seals the class. VB: NotInheritable Class ComputeTax TotalTax = x * .08 End Class C#: sealed class ComputeTax If I wanted to force someone to inherit my abstract class I use MustInherit: VB: MustInherit Class ComputeTax TotalTax = x * .08 End Class C#: abstract class ComputeTax |
An object can be created that inherits the
capabilities of the parent. The new class is called a child class, subclass,
or derived class. I can create a new object like a clone of the
parent. When I create a new button on my form, I am creating a child button
based upon the MS button class that they made for us. That way, all buttons I
make will be the same. Let’s say I want to create a new textbox called
RK_Textbox that will filter what users can type into it. Instead of creating
a new textbox from scratch, I can create my new control based upon a base
class. In this case, Textbox. That way, my new control will have all the
capabilities of the original that comes with VS. Once I define it, I can add my own properties and
methods so it will do everything the original does and more! You can use this technique for any class,
not just controls. You can make a class from scratch and then create another
later based on the first one you made. This saves a huge amount of time as
you can imagine! VB: Public Class RK_Textbox Inherits
System.Windows.Forms.TextBox End Class C#: class RK_Textbox: System.Windows.Forms.TextBox |
|
Polymorphism |
Polymorphism influences code in three ways: ·
As a
feature of Inheritance we create child objects from parent objects. Polymorphism allows us to create a new object
based on a base (parent) class then treat that new object (child) just like
the original. A child class can also have its own version of the parent’s
property or method. I can use the same name but substitute my own function
for the original or base function. Using the same name keeps things
consistent. Developers can choose whether to let someone
override or substitute their method for the original. If my method starts
with Overridable then they can. If
I use NotOverridable when I define
the method they cannot. Class Customer Public Overridable Sub
GetZipCode ‘get the zip code here End Sub End Class C#: class Rectangle : Shape{ ·
Overloading
allows multiple versions (signatures) of the same method. See my discussion
about constructors. ·
Shadowing
(VB Only) lets you substitute arguments & return types for the one
in the base class but still use the same name. |
I can create a new class that inherits from the customer
class. But I want the GetZipCode method of this new class to do something
different than the way the original works. Polymorphism lets me do this. Class Customer Public Overridable Sub
GetZipCode () ‘get the zip code here End Sub End Class Class NewCustomer Inherits Customer Public Overrides Sub
GetZipCode() ‘do something different with
zip code here End Sub End Class Notice
how two Subs, named the same can be used to over-rule the original. But, the
overriding class MUST use the same list of arguments as the base class! I CAN call the original method using
MyBase.GetZipCode if I need to. I can substitute my new Sub for the original and
keep only the same name if I use the SHADOWS
modifier like this: VB: Public Shadows GetZipCode ( C# does not allow this. You can only change
access level and the return type. The arguments must be the same.
Private Function DoFormat (x as Int16) As String Return FormatNumber(x, 2) End Function Private Function DoFormat (x as Int16 , y as
Int16) As String Dim Answer as Integer = x + y Return FormatNumber(Answer,
2) End Function |
|
Members
& Scope |
|
Access
Modifiers That Determine Scope Options in VB.net: PUBLIC means the members can be accessed from any class
or other assembly. PRIVATE means the method/property/variable is only
accessible to the class where they are defined. They are not accessible
from inherited classes. PROTECTED means the member can be accessed from
the same class & any inherited class. FRIEND makes members accessible to classes in the current
assembly. PROTECTED FRIEND means the member can be
accessed from the same class, inherited class, or classes in current
assembly. SHARED (Static) means the method can be accessed
without instantiating the entire object. VB: Public Shared Function DoMath() as Boolean C#: public static bool IsPresent(txtZip) In C#, Friend is replaced with
INTERNAL. |