Notes Collection Related With Oops

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 135

Object-Oriented Programming Concepts

What Is an Object?
What Is a Class?
What Is Inheritance?
What Is an Interface?
What Is a Package?
Questions and Exercises

Lesson: Object-Oriented Programming


Concepts
If you've never used an object-oriented programming language before, you'll need to learn a
few basic concepts before you can begin writing any code. This lesson will introduce you to
objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these
concepts relate to the real world, while simultaneously providing an introduction to the
syntax of the Java programming language.

What Is an Object?

An object is a software bundle of related state and behavior. Software objects are often used
to model the real-world objects that you find in everyday life. This lesson explains how state
and behavior are represented within an object, introduces the concept of data encapsulation,
and explains the benefits of designing your software in this manner.

What Is a Class?

A class is a blueprint or prototype from which objects are created. This section defines a class
that models the state and behavior of a real-world object. It intentionally focuses on the
basics, showing how even a simple class can cleanly model state and behavior.

What Is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and structuring your
software. This section explains how classes inherit state and behavior from their superclasses,
and explains how to derive one class from another using the simple syntax provided by the
Java programming language.

What Is an Interface?

An interface is a contract between a class and the outside world. When a class implements an
interface, it promises to provide the behavior published by that interface. This section defines
a simple interface and explains the necessary changes for any class that implements it.

What Is a Package?

A package is a namespace for organizing classes and interfaces in a logical manner. Placing
your code into packages makes large software projects easier to manage. This section
explains why this is useful, and introduces you to the Application Programming Interface
(API) provided by the Java platform.
Questions and Exercises: Object-Oriented Programming Concepts

Use the questions and exercises presented in this section to test your understanding of
objects, classes, inheritance, interfaces, and packages.

What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and
you'll find many examples of real-world objects: your dog, your desk, your television set,
your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs have
state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles
also have state (current gear, current pedal cadence, current speed) and behavior (changing
gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-
world objects is a great way to begin thinking in terms of object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate area.
For each object that you see, ask yourself two questions: "What possible states can this object
be in?" and "What possible behavior can this object perform?". Make sure to write down your
observations. As you do, you'll notice that real-world objects vary in complexity; your
desktop lamp may have only two possible states (on and off) and two possible behaviors (turn
on, turn off), but your desktop radio might have additional states (on, off, current volume,
current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan,
and tune). You may also notice that some objects, in turn, will also contain other objects.
These real-world observations all translate into the world of object-oriented programming.

A software object.

Software objects are conceptually similar to real-world objects: they too consist of state and
related behavior. An object stores its state in fields (variables in some programming
languages) and exposes its behavior through methods (functions in some programming
languages). Methods operate on an object's internal state and serve as the primary mechanism
for object-to-object communication. Hiding internal state and requiring all interaction to be
performed through an object's methods is known as data encapsulation — a fundamental
principle of object-oriented programming.
Consider a bicycle, for example:

A bicycle modeled as a software object.

By attributing state (current speed, current pedal cadence, and current gear) and providing
methods for changing that state, the object remains in control of how the outside world is
allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears
could reject any value that is less than 1 or greater than 6.

Bundling code into individual software objects provides a number of benefits, including:

1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can be
easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software
developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust to run
in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be problematic,
you can simply remove it from your application and plug in a different object as its
replacement. This is analogous to fixing mechanical problems in the real world. If a
bolt breaks, you replace it, not the entire machine.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle was
built from the same set of blueprints and therefore contains the same components. In object-
oriented terms, we say that your bicycle is an instance of the class of objects known as
bicycles. A class is the blueprint from which individual objects are created.

The following Bicycle class is one possible implementation of a bicycle:

class Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+"
gear:"+gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this
class is based on the previous discussion of bicycle objects. The fields cadence, speed, and
gear represent the object's state, and the methods (changeCadence, changeGear, speedUp
etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because
it's not a complete application; it's just the blueprint for bicycles that might be used in an
application. The responsibility of creating and using new Bicycle objects belongs to some
other class in your application.

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their
methods:

class BicycleDemo {
public static void main(String[] args) {

// Create two different Bicycle objects


Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on those objects


bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();

bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

What Is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain
bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles
(current speed, current pedal cadence, current gear). Yet each also defines additional features
that make them different: tandem bicycles have two seats and two sets of handlebars; road
bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them
a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior
from other classes. In this example, Bicycle now becomes the superclass of MountainBike,
RoadBike, and TandemBike. In the Java programming language, each class is allowed to have
one direct superclass, and each superclass has the potential for an unlimited number of
subclasses:

A hierarchy of bicycle classes.


The syntax for creating a subclass is simple. At the beginning of your class declaration, use
the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to
focus exclusively on the features that make it unique. This makes code for your subclasses
easy to read. However, you must take care to properly document the state and behavior that
each superclass defines, since that code will not appear in the source file of each subclass.

What Is an Interface?
As you've already learned, objects define their interaction with the outside world through the
methods that they expose. Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the interface between you and the
electrical wiring on the other side of its plastic casing. You press the "power" button to turn
the television on and off.

In its most common form, an interface is a group of related methods with empty bodies. A
bicycle's behavior, if specified as an interface, might appear as follows:

interface Bicycle {

void changeCadence(int newValue); // wheel revolutions per minute

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);


}
To implement this interface, the name of your class would change (to a particular brand of
bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the
class declaration:
class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}
Implementing an interface allows a class to become more formal about the behavior it
promises to provide. Interfaces form a contract between the class and the outside world, and
this contract is enforced at build time by the compiler. If your class claims to implement an
interface, all methods defined by that interface must appear in its source code before the class
will successfully compile.
Note: To actually compile the ACMEBicycle class, you'll need to add the public keyword to
the beginning of the implemented interface methods. You'll learn the reasons for this later in
the lessons on Classes and Objects and Interfaces and Inheritance.

What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually
you can think of packages as being similar to different folders on your computer. You might
keep HTML pages in one folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be composed of hundreds or
thousands of individual classes, it makes sense to keep things organized by placing related
classes and interfaces into packages.

The Java platform provides an enormous class library (a set of packages) suitable for use in
your own applications. This library is known as the "Application Programming Interface", or
"API" for short. Its packages represent the tasks most commonly associated with general-
purpose programming. For example, a String object contains state and behavior for
character strings; a File object allows a programmer to easily create, delete, inspect,
compare, or modify a file on the filesystem; a Socket object allows for the creation and use
of network sockets; various GUI objects control buttons and checkboxes and anything else
related to graphical user interfaces. There are literally thousands of classes to choose from.
This allows you, the programmer, to focus on the design of your particular application, rather
than the infrastructure required to make it work.

The Java Platform API Specification contains the complete listing for all packages,
interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition.
Load the page in your browser and bookmark it. As a programmer, it will become your single
most important piece of reference documentation.

Questions and Exercises: Object-Oriented


Programming Concepts
Questions

1. Real-world objects contain ___ and ___.


2. A software object's state is stored in ___.
3. A software object's behavior is exposed through ___.
4. Hiding internal data from the outside world, and accessing it only
through publicly exposed methods is known as data ___.
5. A blueprint for a software object is called a ___.
6. Common behavior can be defined in a ___ and inherited into a ___
using the ___ keyword.
7. A collection of methods with no implementation is called an ___.
8. A namespace that organizes classes and interfaces by functionality is
called a ___.
9. The term API stands for ___?

Exercises

1. Create new classes for each real-world object that you observed at the
beginning of this trail. Refer to the Bicycle class if you forget the required
syntax.
2. For each new class that you've created above, create an interface that
defines its behavior, then require your class to implement it. Omit one or two
methods and try compiling. What does the error look like?

Check your answers.


This article is going to cover three methods of programming: Object
Oriented, Aspect Oriented, and Procedural. Of course, these styles have
their benefits and their liabilities. But solutions often combine all
these styles, in order to create the most managed code.<br>
<br>
To those of you who know me: You know that I'm not much of a writer. I
keep it on more of a "layman's terms" basis, keeping it short and to the
point. This is why I'll be offering a demonstration, using the widely
known "fizz buzz" example: Print numbers 1 to 100, printing "fizz" if
the number is a multiple of 3, "buzz" if it is a multiple of 5, and
"fizz buzz" if it is divisible by both 3 <strong class="bbc">and</strong>
5.<br>
<strong class="bbc">NOTE:</strong> The solution offered <em
class="bbc">will</em>
be a little impractical. I need to break it down into more functions
than necessary, to demonstrate the various styles. At the end of this
entry, I'll provide a final solution, which is the simplest possible.

So what are they, put simply?

Object Oriented Programming: A style of programming which is based


around objects. This is the most common style of programming in the industry.

Aspect Oriented Programming: Often written to complement an OOP


solution. Hard to explain in short, but basically, it's main use is to keep your OOP
code organised, without having to scatter various aspects of code across several
objects.

Procedural Programming: This is the "old school" style of programming. Less


commonly used now~ The main language (which is still used within the industry)
which still focuses on this style is C.

These sound interesting. How do I know which is best for me?


Like I already said, solutions often combine these styles. The whole purpose is to
create code that is well managed. Time to get into the more nitty-gritty stuff~

Procedural Programming
Like I said, this is much less common than object oriented programming
nowadays. However, this doesn't mean that procedural programming is without
benefits! In fact, the main reason that I like C++ is that it allows the programmer
to combine procedural programming with OOP. procedural programming is also
known as "Functional Programming."

Basically, procedural programming is entirely a 1-way system. There's no major


data grouping (the main benefit of OOP) so you're basically working with nothing
more than variables, loops, and functions. (Everything but objects, basically)

The obvious benefit to procedural programming is that you don't need objects for
everything. Take a look at Java, as an example. Everything has to be contained
within a class. What about if you just want one function to do something really
simple? (Obviously, this is also a drawback of OOP, so you'll be reading this again
in a bit)
The main drawback is that there is no major data grouping. With an object
oriented language, it's easy to keep everything organised~ Variables and
methods go in the appropriate classes.

Here's the previously mentioned example. Remember, this is not the best way to
tackle this problem. It's been broken down into various functions to create a
better demonstration.

The key point to notice here is that our variable has to be passed around to
various functions. OK, so this could be solved by a global variable, but no one
likes global variables...

01 #include <stdio.h>
02
03 // no objects here!
04

05 void FizzBuzz(); // our function to perform the fizz buzz operation


06 bool ByThree(int); // a function to check if a number is divisible by 3
07 bool ByFive(int); // a function to check if a number is divisible by 5
08 void PrintFizz(); // a function to print the word "Fizz"
09 void PrintBuzz(); // a function to print the word "Buzz"
10

11 int main() {
12 FizzBuzz();
13 return 0;
14 }

15
16 void FizzBuzz() {
17 int i = 1;
18 for (i; i <= 100; i++) {
19 if (ByThree(i)) PrintFizz();
20 if (ByFive(i)) PrintBuzz();
21 if (!ByThree(i) && !ByFive(i))
22 printf("%d", i);

23
24 printf("\n");
25 }
26 }

27
28 bool ByThree(int x) {return (x % 3 == 0 ? true : false);}
29 bool ByFive(int x) {return (x % 5 == 0 ? true : false);}
30 void PrintFizz() {printf("fizz");}
31 void PrintBuzz() {printf("buzz");}
For more information: http://en.wikipedia....ral_programming

Object Oriented Programming


OOP is a great way to manage your data. Put simply, it's a way to store
variables, and methods together, to create an object. When creating your
objects, you'll have to take into account how this object is going to need to
interact with various other objects. This could be considered a disadvantage,
since it takes more planning. Also, it can sometimes be awkward to come up with
the best way for your object to interact with another.

Remember the key benefit of procedural programming? Well it's time for a
reminder.
When programming in a language which is purely based around OO concepts
(such as Java) then you might run into a bit of an annoying problem. What if you
have a method to do something, which doesn't specifically belong in any of your
classes? Maybe it can be applied to more than one of your classes~ Why rewrite
it in each class? However, there are solutions to this. One way would be to use a
"general" class, and call the methods from this class each time. Another way is
to create a base class, containing these general methods. Then, each of your
objects which require the method will inherit it from the base class.

Time for that example again. The key thing to notice now is that we no longer
need to pass that variable around everywhere. It simply gets accessed from
within the object.

01 #include <cstdio>
02

03 class FizzBuzz {
04 public: // our publicly accessable stuff
void Execute(); // our function to perform the fizz buzz
05
operation
06 public: // our private stuff, that only the class really needs

07 int i; // the variable which we will use in our loop


bool ByThree(); // a function to check if a number is divisible by
08
3
bool ByFive(); // a function to check if a number is divisible by
09
5
10 void PrintFizz(); // a function to print the word "Fizz"
11 void PrintBuzz(); // a function to print the word "Buzz"
12 };

13
14 void FizzBuzz::Execute() {
15 this->i = 1;
16 for (i; i <= 100; i++) {
17 if (this->ByThree()) this->PrintFizz();
18 if (this->ByFive()) this->PrintBuzz();
19 if (!this->ByThree() && !this->ByFive())
20 printf("%d", i);

21
22 printf("\n");
23 }
24 }

25
26 bool FizzBuzz::ByThree() {return (this->i % 3 == 0 ? true : false);}
27 bool FizzBuzz::ByFive() {return (this->i % 5 == 0 ? true : false);}
28 void FizzBuzz::PrintFizz() {printf("fizz");}
29 void FizzBuzz::PrintBuzz() {printf("buzz");}
30

31 int main() {
32 FizzBuzz *fb;
33 fb->Execute();
34 return 0;
35 }
For more information: http://en.wikipedia....ted_programming

Aspect Oriented Programming


Basically, AOP is used to separate your solution into various aspects. It best
complements OOP concepts, as previously stated.

AOP is used to allow an application to grow as time progresses. It allows a


programmer to modify a static object-oriented solution to create a system which
is capable of growing and meeting new requirements.

Consider AOP to be a way to meet requirements which are later added to a


specification. You will develop an object-oriented solution for a client, and a few
years later, your client comes back to you, asking you to alter the application to
meet some new requirements. Rather than going through all the old code, you
will dynamically change the application.

No demonstrations here. The best way to explain is with an example of


something other than code.

The best way to explain AOP is to compare it to an object in the real world.
Consider a packet of crisps. (That's potato chips, if you're in America )
The manufacturers are always reducing the salt content, and making them taste
better, right? Do you think they start from scratch when they make these
changes?
More likely, they would make alterations, instead of completely re-inventing the
flavour.

For more information: http://en.wikipedia....ted_programming

And after all that, we're finally done! Thanks for reading!
Procedural, functional, and imperative programming styles are very similar.

Not really.

There is imperative programming and declarative programming. They are different.

Imperative programming tells the computer how to do something. It involves algorithms, a


step by step description of what is to be done.

Declarative programming tells the computer what to do, but not how to do it in details.

Procedural and Object Oriented programming are Imperative.

Functional programming is Declarative.

Procedural and OO are very similar. Just replace "variable" with "attribute", "procedure or
function" with "method", etc. Just look at the code and you will see they are almost the same.

A pure functional language has no side effects. A side effect would be something like storing
a value in some place in memory or printing something on the screen. This means that each
function takes parameters and gives back results, only that. And a program is a chain of
functions where the results of one are the parameters of another.

This is really old, but this: "Like I said, this is much less common than object
oriented programming nowadays. However, this doesn't mean that procedural
programming is without benefits! In fact, the main reason that I like C++ is that
it allows the programmer to combine procedural programming with OOP.
procedural programming is also known as "Functional Programming." is really,
really wrong.

I'm not sure you quite understand what functional programming is (or at least
you didn't at this time). I'm a bit surprised you haven't corrected this by now. It
could seriously mislead people on this site.

Languages with object-oriented features [oop


languages]
• ABAP • Omnis Studio
• Ada 95 • Oz
• AmigaE o Mozart Programming System
• BETA • Perl since v5
• Blue • PHP5
• Boo • Pliant
• C++ • PRM
• C# • Prototype-based languages
• COBOL o Actor-Based Concurrent
• Cobra Language, ABCL: ABCL/1,
• ColdFusion ABCL/R, ABCL/R2, ABCL/c+
• Common Lisp o Agora
• COOL o Cecil
• CorbaScript o Cel
• Clarion
• CLU o ECMAScript
• Curl  ActionScript
• D  JavaScript
• Dylan  JScript
• E o Etoys in Squeak
• Eiffel o Io
o Sather o Lua
• Falcon o Lisaac
• FreeBASIC o MOO
• F-Script o NewtonScript
• F# o Obliq
• Fortran 2003 o REBOL
• FPr o Self
• Gambas • Python
• Graphtalk • REALbasic
• IDLscript • Revolution
• J • Ruby
• JADE • Scala
• Java • SenseTalk
o Groovy • Simula
o Join Java • Smalltalk
o X10 o Self
• Lasso o Bistro
• Lava o Squeak
• Lexico • S
• Lingo o R
• LISP • Squirrel
• Logtalk • Superx++
• MATLAB • TADS
• Modula-2 • Ubercode
o Modula-3 • Visual Basic
• Nemerle o Visual Basic .NET (VB.NET)
• Noop o VBScript
• NetRexx o Visual Basic for Applications
• Oberon (Oberon-1) (VBA)
o Oberon-2 • Visual FoxPro
• Object Pascal • Visual Prolog
o Delphi • Tcl
o Free Pascal o Xotcl similar to CLOS
o Turbo Pascal o Snit uses delegation
• Object REXX o incr Tcl (itcl) similar to C++
• Objective-C • XBase++ extends xBase standard
language
• Objective Caml
• ZZT-oop
List of object-oriented programming terms
A

• Abstract class
• Abstract method
• Abstraction (computer science)
• Access control
• Accessor method
• Allocated class
• Aspect-oriented

[edit] B

• Bridge pattern
• Builder pattern
• Base class

[edit] C

• Cascaded message
• Cast
• Chain of Responsibility Pattern
• Class
• Class hierarchy
• Class method
• Class object
• Cohesion
• Collaborator
• Collection class
• Composition
• Constructor
• Container (data structure)
• Contravariance
• Copy constructor
• Coupling
• Covariance

[edit] D

• Data-driven design
• Data hiding
• Default constructor
• Deep copy
• Delegation
• Dependency injection
• Destructor
• Dispatch table
• Dynamic binding (computer science) (also called Late Binding)
• Dynamic class
• Dynamic dispatch
• Dynamically typed language
• Dynamic variable
[edit] E

• Early binding
• European Conference on Object-Oriented Programming
• Encapsulation (computer science)
• Exception handling

[edit] F

• Facade - pattern
• Factory method pattern
• Factory object
• Factory pattern
• Finalizer
• First-class function
• Fragile base class
• Function composition

[edit] G

• Generic Programming

[edit] H

• Heap-based memory allocation


• Hybrid language

[edit] I

• Immutable object (also called immutable value)


• Information hiding
• Inheritance (computer science)
• Initialize
• In-line function
• Inner class
• Instance
• Instance method
• Instance variable (also called data member)
• Interaction diagram
• Interface (computer science)
• Inversion of control
• Iterator

[edit] L

• Late binding
• Liskov substitution principle

[edit] M

• Message passing
• Message selector (also called method selector)
• Metaclass
• Metaprogramming
• Method designator
• Method lookup
• Mixin
• Mock object
• Model–view–controller
• Modular programming
• Multiple dispatch
• Multiple inheritance
• Mutator method
• Mutable variable

[edit] N

• Name mangling
• Namespace
• Native method
• Nested class

[edit] O

• Object (computer science)


• Object hierarchy
• Object type
• OOPSLA – annual conference on Object-Oriented Programming Systems
Language and Application
• Open/closed principle
• Overload
• Orthogonality

[edit] P

• Patterns
• Parametric overloading
• Parameterized classes
• Parnas's principles
• Persistent object
• Policy-based design
• Polymorphic
• Primitive data type
• Verb: to program to (see discussion)
• Programming paradigm
• Protocol
• Prototype-based programming
• Prototype pattern
• Pseudo-variable
• Pure polymorphism
• Pure virtual function (also called pure virtual method)
• Partial class

[edit] R

• Rapid prototyping (rapid application development)


• Recursion
• Reference variable
• Refinement
• Reflection
• Responsibility-driven design
• Reverse polymorphism
• Run-time type information

[edit] S

• Scope
• Shadowed name
• Single-assignment variable
• Singly rooted hierarchy
• Slicing
• Specification class, a class implementing abstract class
• Stack-based memory allocation
• Shallow copy, as opposed to Deep copy
• Single Responsibility Principle
• Static method
• Statically typed language, as opposed to Dynamically typed language
• Strongly typed programming language
• Subclass (also called child class or derived class)
• Subclass coupling
• Principle of substitutability
• Subtype
• Superclass (also called parent class or base class)
• Singleton pattern

[edit] T

• Multitier architecture
• Template method pattern
• Type
• Type conversion (also called Typecasting)
• Trait

[edit] V

• Virtual function (also called virtual method)


• Virtual function pointer (also called virtual method pointer)
• Virtual method table (also called vtable, virtual function table or virtual
method table)
• Virtual inheritance (Object Oriented Programming)
• Virtual class

[edit] W

• Weak reference

[edit] Y

• Yo-yo problem

[edit] Z
List of object-oriented programming terms
Object-oriented design is the process of planning a system of interacting objects for the
purpose of solving a software problem. It is one approach to software design.

Contents
[hide]

• 1 Overview
• 2 Object-oriented design topics
o 2.1 Input (sources) for object-oriented design
o 2.2 Object-oriented concepts
o 2.3 Designing concepts
o 2.4 Output (deliverables) of object-oriented design
o 2.5 Some design principles and strategies
• 3 See also
• 4 References

• 5 External links

[edit] Overview

An object contains encapsulated data and procedures grouped together to represent an entity.
The 'object interface', how the object can be interacted with, is also defined. An object-
oriented program is described by the interaction of these objects. Object-oriented design is
the discipline of defining the objects and their interactions to solve a problem that was
identified and documented during object-oriented analysis.

What follows is a description of the class-based subset of object-oriented design, which does
not include object prototype-based approaches where objects are not typically obtained by
instancing classes but by cloning other (prototype) objects.

[edit] Object-oriented design topics

[edit] Input (sources) for object-oriented design

The input for object-oriented design is provided by the output of object-oriented analysis.
Realize that an output artifact does not need to be completely developed to serve as input of
object-oriented design; analysis and design may occur in parallel, and in practice the results
of one activity can feed the other in a short feedback cycle through an iterative process. Both
analysis and design can be performed incrementally, and the artifacts can be continuously
grown instead of completely developed in one shot.

Some typical input artifacts for object-oriented design are:

• Conceptual model: Conceptual model is the result of object-oriented


analysis, it captures concepts in the problem domain. The conceptual
model is explicitly chosen to be independent of implementation details,
such as concurrency or data storage.
• Use case: Use case is a description of sequences of events that, taken
together, lead to a system doing something useful. Each use case provides
one or more scenarios that convey how the system should interact with
the users called actors to achieve a specific business goal or function. Use
case actors may be end users or other systems. In many circumstances
use cases are further elaborated into use case diagrams. Use case
diagrams are used to identify the actor (users or other systems) and the
processes they perform.

• System Sequence Diagram: System Sequence diagram (SSD) is a picture


that shows, for a particular scenario of a use case, the events that
external actors generate, their order, and possible inter-system events.

• User interface documentations (if applicable): Document that shows and


describes the look and feel of the end product's user interface. It is not
mandatory to have this, but it helps to visualize the end-product and
therefore helps the designer.

• Relational data model (if applicable): A data model is an abstract model


that describes how data is represented and used. If an object database is
not used, the relational data model should usually be created before the
design, since the strategy chosen for object-relational mapping is an
output of the OO design process. However, it is possible to develop the
relational data model and the object-oriented design artifacts in parallel,
and the growth of an artifact can stimulate the refinement of other
artifacts.

[edit] Object-oriented concepts

The five basic concepts of object-oriented design are the implementation level features that
are built into the programming language. These features are often referred to by these
common names:

• Object/Class: A tight coupling or association of data structures with the


methods or functions that act on the data. This is called a class, or object
(an object is created based on a class). Each object serves a separate
function. It is defined by its properties, what it is and what it can do. An
object can be part of a class, which is a set of objects that are similar.

• Information hiding: The ability to protect some components of the object


from external entities. This is realized by language keywords to enable a
variable to be declared as private or protected to the owning class.
• Inheritance: The ability for a class to extend or override functionality of
another class. The so-called subclass has a whole section that is derived
(inherited) from the superclass and then it has its own set of functions and
data.
• Interface: The ability to defer the implementation of a method. The ability
to define the functions or methods signatures without implementing them.
• Polymorphism: The ability to replace an object with its subobjects. The
ability of an object-variable to contain, not only that object, but also all of
its subobjects.

[edit] Designing concepts

• Defining objects, creating class diagram from conceptual diagram: Usually


map entity to class.
• Identifying attributes.

• Use design patterns (if applicable): A design pattern is not a finished


design, it is a description of a solution to a common problem, in a
context[1]. The main advantage of using a design pattern is that it can be
reused in multiple applications. It can also be thought of as a template for
how to solve a problem that can be used in many different situations
and/or applications. Object-oriented design patterns typically show
relationships and interactions between classes or objects, without
specifying the final application classes or objects that are involved.

• Define application framework (if applicable): Application framework is a


term usually used to refer to a set of libraries or classes that are used to
implement the standard structure of an application for a specific operating
system. By bundling a large amount of reusable code into a framework,
much time is saved for the developer, since he/she is saved the task of
rewriting large amounts of standard code for each new application that is
developed.

• Identify persistent objects/data (if applicable): Identify objects that have to


last longer than a single runtime of the application. If a relational database
is used, design the object relation mapping.

• Identify and define remote objects (if applicable).

[edit] Output (deliverables) of object-oriented design

• Sequence Diagrams: Extend the System Sequence Diagram to add specific


objects that handle the system events.

A sequence diagram shows, as parallel vertical lines, different processes


or objects that live simultaneously, and, as horizontal arrows, the
messages exchanged between them, in the order in which they occur.

• Class diagram: A class diagram is a type of static structure UML diagram


that describes the structure of a system by showing the system's classes,
their attributes, and the relationships between the classes. The messages
and classes identified through the development of the sequence diagrams
can serve as input to the automatic generation of the global class diagram
of the system.

[edit] Some design principles and strategies

• Dependency injection: The basic idea is that if an object depends upon


having an instance of some other object then the needed object is
"injected" into the dependent object; for example, being passed a
database connection as an argument to the constructor instead of
creating one internally.
• Acyclic dependencies principle: The dependency graph of packages or
components should have no cycles. This is also referred to as having a
directed acyclic graph. [2] For example, package C depends on package B,
which depends on package A. If package A also depended on package C,
then you would have a cycle.
• Composite reuse principle: Favor polymorphic composition of objects over
inheritance
Programming paradigms

• Agent-oriented
• Component-based
o Flow-based
o Pipelined
• Concatenative
• Concurrent computing
• Data-driven
• Declarative (contrast: Imperative)
o Constraint
o Functional
o Dataflow
 Cell-oriented (spreadsheets)
 Reactive
o Logic
 Abductive logic
 Constraint logic
 Functional logic
 Inductive logic
• Event-driven
o Service-oriented
o Time-driven
• Expression-oriented
• Feature-oriented
• Function-level (contrast: Value-level)
• Generic
• Imperative (contrast: Declarative)
o Procedural
• Language-oriented
o Domain-specific
o Grammar-oriented
 Dialecting
o Intentional
• Metaprogramming
o Automatic
o Reflective
 Attribute-oriented
o Template
 Policy-based
• Non-structured (contrast: Structured)
o Array (contrast: Scalar)
o Iterative
• Nondeterministic
• Parallel computing
o Process-oriented
• Programming in the large/small
• Semantic
• Structured (contrast: Non-structured)
o Modular (contrast: Monolithic)
o Object-oriented
 Automata-based
 By separation of concerns:
 Aspect-oriented
 Role-oriented
 Subject-oriented
 Class-based
 Prototype-based
o Recursive
• Value-level (contrast: Function-level)

Object-oriented programming
Object-oriented programming (OOP) is a programming paradigm using "objects" – data
structures consisting of data fields and methods together with their interactions – to design
applications and computer programs. Programming techniques may include features such as
data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.
Many modern programming languages now support OOP.

Contents
[hide]

• 1 Overview
• 2 History
• 3 Fundamental concepts and features
o 3.1 Decoupling
• 4 Formal semantics
• 5 OOP languages
o 5.1 OOP in dynamic languages
• 6 Design patterns
o 6.1 Inheritance and behavioral subtyping
o 6.2 Gang of Four design patterns
o 6.3 Object-orientation and databases
o 6.4 Matching real world
o 6.5 OOP and control flow
o 6.6 Responsibility vs. data-driven design
• 7 The value of object orientation
• 8 See also
• 9 References
• 10 Further reading

• 11 External links

[edit] Overview

Many people first learn to program using a language that is not object-oriented. Simple, non-
OOP programs may be one long list of commands. More complex programs will group lists
of commands into functions or subroutines each of which might perform a particular task.
With designs of this sort, it is common for the program's data to be accessible from any part
of the program. As programs grow in size, allowing any function to modify any piece of data
means that bugs can have wide-reaching effects.
By contrast, the object-oriented approach encourages the programmer to place data where it
is not directly accessible by the rest of the program. Instead the data is accessed by calling
specially written 'functions', commonly called methods, which are either bundled in with the
data or inherited from "class objects" and act as the intermediaries for retrieving or modifying
those data. The programming construct that combines data with a set of methods for
accessing and managing those data is called an object.

An object-oriented program will usually contain different types of objects, each type
corresponding to a particular kind of complex data to be managed or perhaps to a real-world
object or concept such as a bank account, a hockey player, or a bulldozer. A program might
well contain multiple copies of each type of object, one for each of the real-world objects the
program is dealing with. For instance, there could be one bank account object for each real-
world account at a particular bank. Each copy of the bank account object would be alike in
the methods it offers for manipulating or reading its data, but the data inside each object
would differ reflecting the different history of each account.

Objects can be thought of as wrapping their data within a set of functions designed to ensure
that the data are used appropriately, and to assist in that use. The object's methods will
typically include checks and safeguards that are specific to the types of data the object
contains. An object can also offer simple-to-use, standardized methods for performing
particular operations on its data, while concealing the specifics of how those tasks are
accomplished. In this way alterations can be made to the internal structure or methods of an
object without requiring that the rest of the program be modified. This approach can also be
used to offer standardized methods across different types of objects. As an example, several
different types of objects might offer print methods. Each type of object might implement
that print method in a different way, reflecting the different kinds of data each contains, but
all the different print methods might be called in the same standardized manner from
elsewhere in the program. These features become especially useful when more than one
programmer is contributing code to a project or when the goal is to reuse code between
projects.

Object-oriented programming has roots that can be traced to the 1960s. As hardware and
software became increasingly complex, manageability often became a concern. Researchers
studied ways to maintain software quality and developed object-oriented programming in part
to address common problems by strongly emphasizing discrete, reusable units of
programming logic[citation needed]. The technology focuses on data rather than processes, with
programs composed of self-sufficient modules ("classes"), each instance of which ("objects")
contains all the information needed to manipulate its own data structure ("members"). This is
in contrast to the existing modular programming that had been dominant for many years that
focused on the function of a module, rather than specifically the data, but equally provided
for code reuse, and self-sufficient reusable units of programming logic, enabling
collaboration through the use of linked modules (subroutines). This more conventional
approach, which still persists, tends to consider data and behavior separately.

An object-oriented program may thus be viewed as a collection of interacting objects, as


opposed to the conventional model, in which a program is seen as a list of tasks (subroutines)
to perform. In OOP, each object is capable of receiving messages, processing data, and
sending messages to other objects. Each object can be viewed as an independent "machine"
with a distinct role or responsibility. The actions (or "methods") on these objects are closely
associated with the object. For example, OOP data structures tend to 'carry their own
operators around with them' (or at least "inherit" them from a similar object or class).
[edit] History

The terms "objects" and "oriented" in something like the modern sense of object-oriented
programming seem to make their first appearance at MIT in the late 1950s and early 1960s.
In the environment of the artificial intelligence group, as early as 1960, "object" could refer
to identified items (LISP atoms) with properties (attributes);[1][2] Alan Kay was later to cite a
detailed understanding of LISP internals as a strong influence on his thinking in 1966.[3]
Another early MIT example was Sketchpad created by Ivan Sutherland in 1960-61; in the
glossary of the 1963 technical report based on his dissertation about Sketchpad, Sutherland
defined notions of "object" and "instance" (with the class concept covered by "master" or
"definition"), albeit specialized to graphical interaction.[4] Also, an MIT ALGOL version,
AED-0, linked data structures ("plexes", in that dialect) directly with procedures, prefiguring
what were later termed "messages", "methods" and "member functions".[5][6]

Objects as a formal concept in programming were introduced in the 1960s in Simula 67, a
major revision of Simula I, a programming language designed for discrete event simulation,
created by Ole-Johan Dahl and Kristen Nygaard of the Norwegian Computing Center in
Oslo.[7] Simula 67 was influenced by SIMSCRIPT and Hoare's proposed "record classes".[5][8]
Simula introduced the notion of classes and instances or objects (as well as subclasses, virtual
methods, coroutines, and discrete event simulation) as part of an explicit programming
paradigm. The language also used automatic garbage collection that had been invented earlier
for the functional programming language Lisp. Simula was used for physical modeling, such
as models to study and improve the movement of ships and their content through cargo ports.
The ideas of Simula 67 influenced many later languages, including Smalltalk, derivatives of
LISP (CLOS), Object Pascal, and C++.

The Smalltalk language, which was developed at Xerox PARC (by Alan Kay and others) in
the 1970s, introduced the term object-oriented programming to represent the pervasive use of
objects and messages as the basis for computation. Smalltalk creators were influenced by the
ideas introduced in Simula 67, but Smalltalk was designed to be a fully dynamic system in
which classes could be created and modified dynamically rather than statically as in Simula
67.[9] Smalltalk and with it OOP were introduced to a wider audience by the August 1981
issue of Byte Magazine.

In the 1970s, Kay's Smalltalk work had influenced the Lisp community to incorporate object-
based techniques that were introduced to developers via the Lisp machine. Experimentation
with various extensions to Lisp (like LOOPS and Flavors introducing multiple inheritance
and mixins), eventually led to the Common Lisp Object System (CLOS, a part of the first
standardized object-oriented programming language, ANSI Common Lisp), which integrates
functional programming and object-oriented programming and allows extension via a Meta-
object protocol. In the 1980s, there were a few attempts to design processor architectures that
included hardware support for objects in memory but these were not successful. Examples
include the Intel iAPX 432 and the Linn Smart Rekursiv.

Object-oriented programming developed as the dominant programming methodology in the


early and mid 1990s when programming languages supporting the techniques became widely
available. These included Visual FoxPro 3.0,[10][11][12] C++[citation needed], and Delphi[citation needed]. Its
dominance was further enhanced by the rising popularity of graphical user interfaces, which
rely heavily upon object-oriented programming techniques. An example of a closely related
dynamic GUI library and OOP language can be found in the Cocoa frameworks on Mac OS
X, written in Objective-C, an object-oriented, dynamic messaging extension to C based on
Smalltalk. OOP toolkits also enhanced the popularity of event-driven programming (although
this concept is not limited to OOP). Some[who?] feel that association with GUIs (real or
perceived) was what propelled OOP into the programming mainstream.
At ETH Zürich, Niklaus Wirth and his colleagues had also been investigating such topics as
data abstraction and modular programming (although this had been in common use in the
1960s or earlier). Modula-2 (1978) included both, and their succeeding design, Oberon,
included a distinctive approach to object orientation, classes, and such. The approach is
unlike Smalltalk, and very unlike C++.

Object-oriented features have been added to many existing languages during that time,
including Ada, BASIC, Fortran, Pascal, and others. Adding these features to languages that
were not initially designed for them often led to problems with compatibility and
maintainability of code.

More recently, a number of languages have emerged that are primarily object-oriented yet
compatible with procedural methodology, such as Python and Ruby. Probably the most
commercially important recent object-oriented languages are Visual Basic.NET (VB.NET)
and C#, both designed for Microsoft's .NET platform, and Java, developed by Sun
Microsystems. Both frameworks show the benefit of using OOP by creating an abstraction
from implementation in their own way. VB.NET and C# support cross-language inheritance,
allowing classes defined in one language to subclass classes defined in the other language.
Java runs in a virtual machine, making it possible to run on all different operating systems.
VB.NET and C# make use of the Strategy pattern to accomplish cross-language inheritance,
whereas Java makes use of the Adapter pattern[citation needed].

Just as procedural programming led to refinements of techniques such as structured


programming, modern object-oriented software design methods include refinements[citation needed]
such as the use of design patterns, design by contract, and modeling languages (such as
UML).

[edit] Fundamental concepts and features


See also: List of object-oriented programming terms

A survey by Deborah J. Armstrong of nearly 40 years of computing literature identified a


number of "quarks", or fundamental concepts, found in the strong majority of definitions of
OOP.[13]

Not all of these concepts are to be found in all object-oriented programming languages. For
example, object-oriented programming that uses classes is sometimes called class-based
programming, while prototype-based programming does not typically use classes. As a result,
a significantly different yet analogous terminology is used to define the concepts of object
and instance.

Benjamin C. Pierce and some other researchers view as futile any attempt to distill OOP to a
minimal set of features. He nonetheless identifies fundamental features that support the OOP
programming style in most object-oriented languages:[14]

• Dynamic dispatch – when a method is invoked on an object, the object


itself determines what code gets executed by looking up the method at
run time in a table associated with the object. This feature distinguishes
an object from an abstract data type (or module), which has a fixed
(static) implementation of the operations for all instances. It is a
programming methodology that gives modular component development
while at the same time being very efficient.
• Encapsulation (or multi-methods, in which case the state is kept separate)
• Subtype polymorphism
• Object inheritance (or delegation)
• Open recursion – a special variable (syntactically it may be a keyword),
usually called this or self, that allows a method body to invoke another
method body of the same object. This variable is late-bound; it allows a
method defined in one class to invoke another method that is defined
later, in some subclass thereof.

Similarly, in his 2003 book, Concepts in programming languages, John C. Mitchell identifies
four main features: dynamic dispatch, abstraction, subtype polymorphism, and inheritance.[15]
Michael Lee Scott in Programming Language Pragmatics considers only encapsulation,
inheritance and dynamic dispatch.[16]

Additional concepts used in object-oriented programming include:

• Classes of objects
• Instances of classes
• Methods which act on the attached objects.
• Message passing
• Abstraction

[edit] Decoupling

Decoupling allows for the separation of object interactions from classes and inheritance into
distinct layers of abstraction. A common use of decoupling is to polymorphically decouple
the encapsulation,[clarification needed] which is the practice of using reusable code to prevent
discrete code modules from interacting with each other. However, in practice decoupling
often involves trade-offs with regard to which patterns of change to favor. The science of
measuring these trade-offs in respect to actual change in an objective way is still in its
infancy.[citation needed]

[edit] Formal semantics


See also: Formal semantics of programming languages

There have been several attempts at formalizing the concepts used in object-oriented
programming. The following concepts and constructs have been used as interpretations of
OOP concepts:

• coalgebraic data types[dubious – discuss]


• abstract data types (which have existential types) allow the definition of
modules but these do not support dynamic dispatch
• recursive types
• encapsulated state
• Inheritance (object-oriented programming)
• records are basis for understanding objects if function literals can be
stored in fields (like in functional programming languages), but the actual
calculi need be considerably more complex to incorporate essential
features of OOP. Several extensions of System F<: that deal with mutable
objects have been studied;[17] these allow both subtype polymorphism and
parametric polymorphism (generics)

Attempts to find a consensus definition or theory behind objects have not proven very
successful (however, see Abadi & Cardelli, A Theory of Objects[17] for formal definitions of
many OOP concepts and constructs), and often diverge widely. For example, some
definitions focus on mental activities, and some on mere program structuring. One of the
simpler definitions is that OOP is the act of using "map" data structures or arrays that can
contain functions and pointers to other maps, all with some syntactic and scoping sugar on
top. Inheritance can be performed by cloning the maps (sometimes called "prototyping").
OBJECT:=>> Objects are the run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has to
handle.

OOP languages

Simula (1967) is generally accepted as the first language to have the primary features of an
object-oriented language. It was created for making simulation programs, in which what
came to be called objects were the most important information representation. Smalltalk
(1972 to 1980) is arguably the canonical example, and the one with which much of the theory
of object-oriented programming was developed. Concerning the degree of object orientation,
following distinction can be made:

• Languages called "pure" OO languages, because everything in them is


treated consistently as an object, from primitives such as characters and
punctuation, all the way up to whole classes, prototypes, blocks, modules,
etc. They were designed specifically to facilitate, even enforce, OO
methods. Examples: Smalltalk, Eiffel, Ruby, JADE, Emerald.[18]
• Languages designed mainly for OO programming, but with some
procedural elements. Examples: C++, C#, VB.NET, Java, Scala, Python.
(Note: C# and VB.NET are both exclusively part of Microsoft's .NET
Framework development platform and compile to the same intermediate
language (IL). Although there are some construct differences, they are
minimal and in the context of this grouping, some might consider them
part of one language with simply two syntax translation engines).
• Languages that are historically procedural languages, but have been
extended with some OO features. Examples: Visual Basic (derived from
BASIC), Fortran 2003, Perl, COBOL 2002, PHP, ABAP.
• Languages with most of the features of objects (classes, methods,
inheritance, reusability), but in a distinctly original form. Examples:
Oberon (Oberon-1 or Oberon-2).
• Languages with abstract data type support, but not all features of object-
orientation, sometimes called object-based languages. Examples: Modula-
2 (with excellent encapsulation and information hiding), Pliant, CLU.

[edit] OOP in dynamic languages

In recent years, object-oriented programming has become especially popular in dynamic


programming languages. Python, Ruby and Groovy are dynamic languages built on OOP
principles, while Perl and PHP have been adding object oriented features since Perl 5 and
PHP 4, and ColdFusion since version 6.

The Document Object Model of HTML, XHTML, and XML documents on the Internet have
bindings to the popular JavaScript/ECMAScript language. JavaScript is perhaps the best
known prototype-based programming language, which employs cloning from prototypes
rather than inheriting from a class. Another scripting language that takes this approach is Lua.
Earlier versions of ActionScript (a partial superset of the ECMA-262 R3, otherwise known as
ECMAScript) also used a prototype-based object model. Later versions of ActionScript
incorporate a combination of classification and prototype-based object models based largely
on the currently incomplete ECMA-262 R4 specification, which has its roots in an early
JavaScript 2 Proposal. Microsoft's JScript.NET also includes a mash-up of object models
based on the same proposal, and is also a superset of the ECMA-262 R3 specification.
[edit] Design patterns

Challenges of object-oriented design are addressed by several methodologies. Most common


is known as the design patterns codified by Gamma et al.. More broadly, the term "design
patterns" can be used to refer to any general, repeatable solution to a commonly occurring
problem in software design. Some of these commonly occurring problems have implications
and solutions particular to object-oriented development.

[edit] Inheritance and behavioral subtyping

See also: Object oriented design

It is intuitive to assume that inheritance creates a semantic "is a" relationship, and thus to
infer that objects instantiated from subclasses can always be safely used instead of those
instantiated from the superclass. This intuition is unfortunately false in most OOP languages,
in particular in all those that allow mutable objects. Subtype polymorphism as enforced by
the type checker in OOP languages (with mutable objects) cannot guarantee behavioral
subtyping in any context. Behavioral subtyping is undecidable in general, so it cannot be
implemented by a program (compiler). Class or object hierarchies need to be carefully
designed considering possible incorrect uses that cannot be detected syntactically. This issue
is known as the Liskov substitution principle.

[edit] Gang of Four design patterns

Main article: Design pattern (computer science)

Design Patterns: Elements of Reusable Object-Oriented Software is an influential book


published in 1995 by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides,
sometimes casually called the "Gang of Four". Along with exploring the capabilities and
pitfalls of object-oriented programming, it describes 23 common programming problems and
patterns for solving them. As of April 2007, the book was in its 36th printing.

The book describes the following patterns:

• Creational patterns (5): Factory Method Pattern, Abstract Factory Pattern,


Singleton Pattern, Builder Pattern, Prototype Pattern
• Structural patterns (7): Adapter Pattern, Bridge Pattern, Composite
Pattern, Decorator Pattern, Facade Pattern, Flyweight Pattern, Proxy
Pattern
• Behavioral patterns (11): Chain of Responsibility Pattern, Command
Pattern, Interpreter Pattern, Iterator Pattern, Mediator Pattern, Memento
Pattern, Observer Pattern, State Pattern, Strategy Pattern, Template
Method Pattern, Visitor Pattern

[edit] Object-orientation and databases

Main articles: Object-Relational impedance mismatch, Object-relational mapping,


and Object database

Both object-oriented programming and relational database management systems (RDBMSs)


are extremely common in software today. Since relational databases don't store objects
directly (though some RDBMSs have object-oriented features to approximate this), there is a
general need to bridge the two worlds. The problem of bridging object-oriented programming
accesses and data patterns with relational databases is known as Object-Relational impedance
mismatch. There are a number of approaches to cope with this problem, but no general
solution without downsides.[19] One of the most common approaches is object-relational
mapping, as found in libraries like Java Data Objects and Ruby on Rails' ActiveRecord.

There are also object databases that can be used to replace RDBMSs, but these have not been
as technically and commercially successful as RDBMSs.

[edit] Matching real world

OOP can be used to translate from real-world phenomena to program elements (and vice
versa). OOP was even invented for the purpose of physical modeling in the Simula 67
language. However, not everyone agrees that direct real-world mapping is facilitated by OOP
(see Criticisms section), or is even a worthy goal; Bertrand Meyer argues in Object-Oriented
Software Construction[20] that a program is not a model of the world but a model of some part
of the world; "Reality is a cousin twice removed". At the same time, some principal
limitations of OOP had been noted.[21] An example for a real world problem that cannot be
modeled elegantly with OOP techniques is the Circle-ellipse problem.

However, Niklaus Wirth (who popularized the adage now known as Wirth's law: "Software is
getting slower more rapidly than hardware becomes faster") said of OOP in his paper, "Good
Ideas through the Looking Glass", "This paradigm closely reflects the structure of systems 'in
the real world', and it is therefore well suited to model complex systems with complex
behaviours" (contrast KISS principle).

However, it was also noted (e.g. in Steve Yegge's essay Execution in the Kingdom of
Nouns[1]) that the OOP approach of strictly prioritizing things (objects/nouns) before actions
(methods/verbs) is a paradigm not found in natural languages.[22] This limitation may lead for
some real world modelling to overcomplicated results compared e.g. to procedural
approaches.[23]

[edit] OOP and control flow

OOP was developed to increase the reusability and maintainability of source code.[24]
Transparent representation of the control flow had no priority and was meant to be handled
by a compiler. With the increasing relevance of parallel hardware and multithreaded coding,
developer transparent control flow becomes more important, something hard to achieve with
OOP.[25][26][27]

[edit] Responsibility vs. data-driven design

Responsibility-driven design defines classes in terms of a contract, that is, a class should be
defined around a responsibility and the information that it shares. This is contrasted by Wirfs-
Brock and Wilkerson with data-driven design, where classes are defined around the data-
structures that must be held. The authors hold that responsibility-driven design is preferable.

[edit] The value of object orientation

A large number of software engineers agree that gathering commands and data into discrete
objects in this way makes their software easier to develop, document and maintain. However,
a significant number of engineers feel the reverse may be true: that software becomes more
complex to maintain and document, or even to engineer from the start. The conditions under
which OOP prevails over alternative techniques (and vice-versa) often remain unstated by
either party, however, making rational discussion of the topic difficult, and often leading to
heated debates[citation needed] over the matter.

A number of well-known researchers and programmers have analysed the utility of OOP.
Here is an incomplete list:

• Luca Cardelli wrote a paper titled "Bad Engineering Properties of Object-Oriented


Languages".[28]
• Richard Stallman wrote in 1995, "Adding OOP to Emacs is not clearly an
improvement; I used OOP when working on the Lisp Machine window systems, and I
disagree with the usual view that it is a superior way to program."[29]
• A study by Potok et al.[30] has shown no significant difference in productivity between
OOP and procedural approaches.
• Christopher J. Date stated that critical comparison of OOP to other technologies,
relational in particular, is difficult because of lack of an agreed-upon and rigorous
definition of OOP.[31] Date and Darwen[32] propose a theoretical foundation on OOP
that uses OOP as a kind of customizable type system to support RDBMS.
• Alexander Stepanov suggested that OOP provides a mathematically-limited viewpoint
and called it "almost as much of a hoax as Artificial Intelligence. I have yet to see an
interesting piece of code that comes from these OO people. In a sense, I am unfair to
AI: I learned a lot of stuff from the MIT AI Lab crowd, they have done some really
fundamental work....".[33]
• Paul Graham has suggested that the purpose of OOP is to act as a "herding
mechanism" that keeps mediocre programmers in mediocre organizations from "doing
too much damage". This is at the expense of slowing down productive programmers
who know how to use more powerful and more compact techniques.[34]
• Joe Armstrong, the principal inventor of Erlang, is quoted as saying "The problem
with object-oriented languages is they've got all this implicit environment that they
carry around with them. You wanted a banana but what you got was a gorilla holding
the banana and the entire jungle."[35]
• Richard Mansfield, author and former editor of COMPUTE! magazine, states that
"like countless other intellectual fads over the years ("relevance", communism,
"modernism", and so on—history is littered with them), OOP will be with us until
eventually reality asserts itself. But considering how OOP currently pervades both
universities and workplaces, OOP may well prove to be a durable delusion. Entire
generations of indoctrinated programmers continue to march out of the academy,
committed to OOP and nothing but OOP for the rest of their lives."[36] He also is
quoted as saying "OOP is to writing a program, what going through airport security is
to flying".[37]
• Rich Hickey, creator of Clojure, described object systems as over simplistic models of
the real world. He emphasized the inability of OOP to model time properly, which is
getting increasingly problematic as software systems become more concurrent.[
vbProgramming Tutorials - OOP
OOP - Object Oriented Programming. This is what everyone uses. Once
you understand the concept you'll see why its extremely useful when
programming. This tutorial will cover very basic OOP so that we can move
on into the animation tutorial.

Starting Up
Create a project called OOP. Go to the solution explorer(on your right). Right click
where it says "OOP"(right above where it says "References", and go to Add | Add New
Item. When you add the item select class, and name it HelloWorld(hmm.. I wonder what
this program is going to do). You'll see what classes are in a moment.

VB.NET automatically generates this code for you:

Public Class HelloWorld

End Class

Well if you go back to where it says Form1, you'll notice that it says:

Public Class Form1

End Class

A class is basically a file which contains variables, subs, and functions that do
something. Classes are useful because they can be reused. For example, let's say we
make a Hello World class. If you give this Hello World class to someone else, and you
tell them to use it, their program will display hello world too. Obviously no one will
distribute a Hello World class, but if you made a whole bunch of subs that checked
collision detection for your game, you could put those subs in a class, and use it for every
level in your game to check for collision detection; the advantage is, once you make it,
you dont have to type anything over again. The collision detection class(which we will, in
fact, make in another tutorial) can be used for every level(or every form) without any
exceptions. You don't need to make any modifications at all, as long as you program it
properly.

Go back to the HelloWorld class. Add this sub:

Public Sub SayHelloWorld()


MessageBox.Show("Hello World")
End Sub

This sub obviously displays "Hello World" in a MessageBox when you call it.
Go back to Form1. Here's how you use a class, this concept might be a little
tricky. Remember, our class name is HelloWorld. In order to use the class, you'd have
to instantiate it, which means you have to create a copy of it.
Dim MyHelloWorldClass As New HelloWorld()
We have to Dim something as the class. For example if you delete this line and go to
Form1_Load, type in HelloWorld followed by a dot. You wont get any popup boxes. You
have to dim it as your class in order to use it. Now try this, take the code above, and
type it in without the New. In form1_load, type in MyHelloWorldClass followed by a
dot. YOu wont get a popup box that has SayHelloWorld in it. This question will come
up every time: why NEW?
Think about it this way. If you're a historian, and you come across an important
document, and you (for some strange reason :-p) want to take notes on it.. you wouldnt!
Its an important artifact, if you take notes on it, or draw on it or something like that, it
might get ruined (this is THE dumbest story.. I know, but I couldnt think of anything
else)! So basically, you have to take a photocopy of it, and THEN take notes on it. In the
same manner, you don't want to use the original class, you want to create a copy of it by
saying New, and then use the copied class. (bad explanation o_O - if anyone can think of
anything better, post it at the forums)

---
Note: 'Stipto' emailed me an alternate explanation for this. He got it from his book,
"Programming in Visual Basic .NET by Julia Case Bradley and Anita C Millspaugh."
The explanation follows:

Many people use a cookie analogy to describe the relationship of a class and an object.
The cookie cutter is the class. You can't eat a cookie cutter, but you can use it to make
cookies; the cookie is the object.When you make a cookie using a cookie cutter, you
instantiate an object of the cookie class. You can use the same cookie cutter to make
various kinds of cookies. Although all the cookies will have the same shape, some may be
chocolate, others are lemon or vanilla; some may be frosted or have colored sprinkles on
top. The characteristics of the cookie, such as flavor and topping, are the properties of
the object.

Thanks Stipto!
---

OK, now that you have the "New" there, go to form1_load and type in
MyHelloWorldClass followed by a dot, and click the box that says "SayHelloWorld".
Easy enough, run your program and obviously you'll get a messagebox that shows
HelloWorld.

That's the simplest class you'll ever use in your entire life :-D. Let's get moving on to
some advanced stuff, this was just to demonstrate basic OOP.

In form1_load, delete the line MyHelloWorldClass.SayHelloWorld() line. Go to


your HelloWorld class. Change the Public Sub SayHelloWorld to a Private sub. Go
back to form1_load and type in the line which you just deleted. As you're typing the dot,
you'll notice that SayHelloWorld is missing... that's becuase it's private. "Well why
would you want it to be private if you can't use it in the form", you might ask. Well, you
can use it within the class - it's not that useful in this program but i'll show you uses for
it in other programs. For now, create a Public Sub Hi in the class. In the sub, type in
SayHelloWorld(). If you go to form1_load and type in MyHelloWorldClass.Hi,
it'll display hello world. What's happening is it's going to the sub Hi, and from that Sub
Hi, it's going to the sub SayHelloWorld.

Some Adcanced Stuff


The program which we just did was completely useless, and there's no reason to
distribute it because anyone can type MessageBox.Show("Hello World") :-). What we're
going to do in this 2nd part of the tutorial is learning about Constructors.
What is a constructor? A constructor is something that is called when you
instantiate(make NEW) an object. A constructor is in the sub New of your class. If we
took that HelloWorld class, and rename sub Hi to sub New, when we Dim
MyHelloWorldClass as New HelloWorld, you get the message. Since we dimmed it in the
globals (at the top of your code), we get the message when the program loads (becuase
global variables are created when the program starts) A constructor is usually used to
pass in Arguments, especially a form. We're going to make a class that changes the
background color of the form with the color you specify. Delete your HelloWorld class
(right click it in the solution explorer and hit delete. Create a new class called
ChangeBackground.

Create this sub:


Public Sub New(ByVal target As Form)
target.BackColor = Color.Red
End Sub

(Note: the "ByVal" is automatically typed in; there's 2 things, byVal and byRef. We'll
learn about that in another tutorial) We pass in an argument called Target, which is our
form. Instead of saying Form1.backcolor = color.red, we specify an argument called
Target which can be used for any form. We know what this does, it just changes the
background color of the specified form to red. Go to form1's code. Type this in:

Dim Change As New ChangeBackground(


While you're typing in the parenthesees, a little popup box tells you "Target As
System.Windows.Forms.Form", meaning that you have to specify a form. In order to
refer to form1, we would just say.. Me!
Dim Change As New ChangeBackground(Me)

Even if you create another form, this will change the background color for every form.
Run your project, and your background color will be Red.

How do we make it so that we change the background color to ANY color we want?
Simple, pass in a color argument.

Public Sub New(ByVal target As Form, ByVal YourColor As Color)


target.BackColor = YourColor
End Sub

Now go back to your Globals area for Form1. Type this in:
Dim Change As New ChangeBackground(Me, Color.Blue)

Run your program and it changes the background color to blue.


This tutorial is a relatively simple one, just to give you an introduction to OOP. The
"Advanced OOP" tutorial will teach you Inheritance, Destructors, PolyMorphism.. etc.

Next Tutorial: Animation! (I'm having trouble with random font changes and no
spacing becuase of the lack of cooperation from DreamWeaver! I keep trying to change
the font, but every time I push 'enter', dreamweaver changes it back....)

The Source Code for this tutorial is located here: You can also locate this by logging in
to vbProgramming Forums and going to:
Tutorials > Tutorial Source Code > Source Code
Object Oriented Programming Tutorial
The following guide was written several years ago whilst I was a student at the Department of
Computer Science at Queen's University, Belfast. It was aimed at students moving from a
procedural Pascal type language (Modula-2) to Object Oriented programming. Since then
many people have found the tutorial useful so it has been slightly updated and remains on the
site.

Table of Contents

• Introduction
• Objects
• Classes
• Inheritance
• Conclusion

• Introduction
• This tutorial aims to teach the basics of Object Oriented Programming. It's designed
for students who have some knowledge of procedural programming. It is not tailored
to any one specific language, although examples in C++ and Java will be given. To
compare OOP with procedural languages, examples using Modula-2 will also be used
- Modula-2 is from the Pascal family of languages so hopefully should be familiar to
most students.
• Probably the most important thing I would like you to take away from this tutorial is
the idea that programming in an object oriented language is more than just learning
new functions, syntax, etc. OOP is more than learning a new language; it requires a
new way of thinking. The idea is to not primarily concentrate on the cornerstones of
procedural languages - data structures and algorithms - but instead think in terms of
objects.
• The best way to learn any language is to practice - Learning a new way of
programming is no different. There are a number of OOP based languages out there,
but for beginners I would recommend starting with either Java or C# (pronounced C-
Sharp). You can start playing with these languages straight away - free compilers and
development environments are available. The tutorial has some examples in C++,
however I don't recommend starting to learn OOP in C++.
• Java is a platform-independent language developed by Sun Microsystems. You can
pick up the Java SDK and begin developing straight away. If you want to have a
complete development environment, you can download the free JBuilder Foundation
from Borland
• C# is a relatively new language developed by Microsoft. C# is one language that
forms part of Microsoft's .NET platform. You can download the .NET SDK which
contains a C# compiler. If you want to develop in C# seriously, you'll need to get hold
of Microsoft Visual Studio - Academic editions are available.
• Next: Objects.

Objects
Objects are the central idea behind OOP. The idea is quite simple.
An object is a bundle of variables and related methods.

A method is similar to a procedure; we'll come back to these later.

The basic idea behind an object is that of simulation. Most programs are written with very
little reference to the real world objects the program is designed to work with; in object
oriented methodology, a program should be written to simulate the states and activities of real
world objects. This means that apart from looking at data structures when modelling an
object, we must also look at methods associated with that object, in other words, functions
that modify the objects attributes.

A few examples should help explain this concept. First, we turn to any student's favourite
pastime...

Drink!

Say we want to write a program about a pint of beer. If we were writing this program in
Modula-2, we could write something like this:

TYPE BeerType = RECORD


BeerName: STRING;
VolumeInPints: REAL;
Colour: ColourType;
Proof: REAL;
PintsNeededToGetYouDrunk: CARDINAL;
...
END;

Now lets say we want to initialise a pint of beer, and take a sip from it. In Modula-2, we
might code this as:

VAR MyPint: BeerType;

BEGIN
...
(* Initialise (i.e. buy) a pint: *)
MyPint.BeerName := "Harp";
MyPint.VolumeInPints := 1.00;
...
...
(* Take a sip *)
MyPint.VolumeInPints := MyPint.VolumeInPints - 0.1;
...

We have constructed this entire model based entirely on data types, that is we defined
BeerType as a record structure, and gave that structure various names, e.g. Name. This is the
norm for procedural programming.

This is however, not how we look at things when we want to program using objects. If you
remember how we defined an object at the start of this section, you will remember that we
must not only deal with data types, but we must also deal with methods.

A method is an operation which can modify an objects behaviour. In


other words, it is something that will change an object by manipulating
its variables.
This means that when we take a real world object, in this case a pint of beer, when we want to
model it using computational objects, we not only look at the data structure that it consists of,
but also all possible operations that we might want to perform on that data. For our example,
we should also define the following methods associated with the BeerType object:

• InitialiseBeer - this should allow us to give our beer a name, a volume,


etc.
• GetVolume - to see how much beer we have left!
• Take_A_Sip - for lunchtime pints...
• Take_A_Gulp - for quick pints...
• Sink_Pint - for post exam pints...

There are loads more methods we could define - we might want a function GetBeerName to
help us order another pint for example. Now, some definitions. An object variable is a single
variable from an object's data structure, for example BeerName is one of BeerType's object
variables. Now the important bit from this section:

Only an object's methods should modify its variables

There are a few exceptions, but we'll cover them much later. What this means in our example
is that unlike the Modula code, we cannot directly modify BeerType's variables - we cannot
set BeerName to "Guinness" directly. We must use the object's methods to do this. In practice,
what this means is that we must think very carefully when we define methods. Say in the
above example we discover when writing the main program that we need to be able to take a
drink of arbitrary size; we cannot do this with the above definition, we can only take a sip, a
gulp etc. We must go back and define a new method associated with BeerType, say
Take_Drink which will take a parameter representing the amount of beer we wish to drink.

Another Example

We'll now deal with a real-life example which will help us understand some more object
concepts. We will design an object to emulate a counter.

A counter is a variable in a program that is used to hold a value. If you don't know that then
you shouldn't be reading this! To make things very simple, we'll assume that our counter has
only three operations associated with it:

• Initialising the counter to a value


• Incrementing the counter by one
• Getting the current value of the counter

So, when we come to implement the above using objects we will define three methods that do
the above.

You may be thinking that we could implement this very simply in Modula-2 using definition
and implementation modules obtaining the same results as if we used an object oriented
language. Well, we nearly can:

DEFINITION MODULE Counter;

PROCEDURE InitialiseCounter(InitialValue: INTEGER);

PROCEDURE IncrementCounter;

PROCEDURE GetCounterValue(): INTEGER;


END Counter.

IMPLEMENTATION MODULE Counter;

VAR MyCounter: INTEGER;

PROCEDURE InitialiseCounter(InitialValue: INTEGER);


BEGIN
MyCounter := InitialValue;
END InitialiseCounter;

PROCEDURE IncrementCounter;
BEGIN
INC(MyCounter);
END IncrementCounter;

PROCEDURE GetCounterValue(): INTEGER;


BEGIN
RETURN MyCounter;
END GetCounterValue;

BEGIN
MyCounter := 0;
END Counter.

Because Modula-2 is not object oriented, this will only satisfy one of the requirements for an
object oriented language - encapsulation. This simply means that we have implemented
information hiding, i.e. we cannot directly access MyCounter from any module that imports
Counter. But being object oriented means a lot more than just encapsulation, as we'll see...

Next: Classes.

Classes
Say we wanted to extend the counter example discussed previously. Perhaps in our Modula-2
program we need three counters. We could define an array of MyCounter and work through
that. Or say we needed up to 1000 counters. Then we could also declare an array, but that
would waste a lot of memory if we only used a few counters. Perhaps if we needed an infinite
amount of counters we could put them in a linked list and allocate memory as required.

The point of all this is that we are talking in terms of data structures; all of the above
discussion has nothing to do with the behaviour of the counter itself. When programming
with objects we can ignore anything not directly concerning the behaviour or state of an
object; we instead turn our attention to classes.

A class is a blueprint for an object.

What this basically means is that we provide a blueprint, or an outline of an object. This
blueprint is valid whether we have one or one thousand such objects. A class does not
represent an object; it represents all the information a typical object should have as well as all
the methods it should have. A class can be considered to be an extremely extended TYPE
declaration, since not only are variables held but methods too.
C++

As an example, lets give the C++ class definition for our counter object.

class Counter {

private:
int MyCounter

public:
Counter() {
MyCounter = 0;
}

void InitialiseCounter(int value) {


MyCounter = value;
}

void IncrementCounter() {
MyCounter++;
}

int GetCounterValue() {
return (MyCounter);
}
}

A lot to go through for this little example. You really need to understand the fundamentals of
C before the example will make any sense.

• In the private section, all the objects variables should be placed. These
define the state of the object. As the name suggests, the variables are
going to be private, that is they cannot be accessed from outside the class
declaration. This is encapsulation.
• The public section contains all the object's methods. These methods, as
the name suggests, can be accessed outside the class declaration. The
methods are the only means of communication with the object.
• The methods are implemented as C++ functions or procedures; the three
methods should be easy to understand.
• All class definitions should also have one public method that has the same
name as the class itself, in this case Counter. This method is called the
class constructor, and will be explained soon.
• Functions and procedures can also be placed in the private section; these
will not be accessible to the outside world but only within the class
declaration. This can be used to provide support routines to the public
routines.

Instantiation

This is an awful big word for a powerfully simple concept. All we have done so far is to
create a class, i.e. a specification for our object; we have not created our object yet. To create
an object that simulates a counter in C++ then, all we have to do is declare in our main
program:

Counter i;

Although this seems just like an ordinary variable declaration, this is much more. The
variable i now represents an instance of the counter type; a counter object. We can now
communicate with this object by calling its methods, for example we can set the counter to
the value '50' by calling i.InitialiseCounter(50);. We can increment the counter -
i.IncrementCounter(); - and we can get the counter value - int value =
i.GetCounterValue();.

When we first instantiate an object (i.e. when we first declare, or create it), the class
constructor is called. The class constructor is the method with the same name as the class
definition. This method should contain any start-up code for the object; any initialisation of
object variables should appear within this method. In the counter example, whenever we
create a new counter object, the first thing that happens to the object is that the variable
MyCounter is initialised to zero.

Remember the question posed at the very start? The power of objects starts to kick in now.
Say we require another counter within our program. All we have to do is declare a new
object, say:

Counter j;

Although the new counter shares the same blueprint as the previous object, it shares none of
the same data. What this means is that i and j are two distinct objects, each with their own
separate values. We can increment them independently, for example. Should we need 1000
counter objects we could declare an array of counter objects:

Counter loads[1000];

and then initialize one of them using a call such as loads[321].InitialiseCounter();.

Java

The equivalent Java class definition for the counter example follows. It is remarkably similar
to the C++ definition, and differs only in syntax.

class Counter extends Object {

private int MyCounter;

Counter() {
MyCounter = 0;
}

public void InitialiseCounter(int value) {


MyCounter = value;
}

public void IncrementCounter(void) {


MyCounter++;
}

public int GetCounterValue(void) {


return (MyCounter);
}
}

A few brief notes about the differences:

• All new classes must be defined with the extension extends Object. This
defines the superclass; this will be dealt with in the next section.
• There are no public or private sections, instead all variables and methods
are prefixed with the appropriate public or private qualifier.
• The class constructor definition remains the same.

Instantiating objects in Java is slightly different; objects are declared differently:

Counter i;

i = new Counter();

Basically we define a variable to reference the object in the first line. Then we actually create
an instance of the object by a call to new in the second line. Accessing object methods is done
in the exact same way in Java as in C++.

Why Bother?

The process of designing and programming objects seems very cumbersome, so why bother?
Well, it's difficult to see from such a small example, but for larger projects, OOP techniques
allow a great deal of flexibility. OOP is used for the following reasons.

• Encapsulation: in our example we cannot alter the value of the counter


other than by incrementing it or setting it to a initial value. This drastically
helps with understanding of the code and eliminating potential bugs.
• Modularity: Different programmers or teams can work on different
independent objects.
• Inheritance: this is covered in the next section.

Next: Inheritance.

Inheritance
Another big word for a simple concept. To help explain inheritance, we'll go back to our beer
example. Say we want to define a new class to represent a pint of an imported French beer.
This class would have all the variables and methods of the normal beer class, but it would
have the following additional information:

• A variable representing the price of the beer


• Two methods to set and get the price of the beer

(We need this information because we are students; everyone knows the price of Harp, but
we would like to know the price of this expensive beer before we order it!)

It would be rather tedious to define a new class, FrenchBeerType which had all the variables
and methods of BeerType plus the few extra we needed. Instead, we can define
FrenchBeerType to be a subclass of BeerType.

A subclass is a class definition which derives functionality from another


class definition.

What this means is that we only need to define the additional information that the
FrenchBeerType class has.
So, we create a new class, FrenchBeerType, and tell our compiler that it is a subclass of
BeerType. In the class definition, we would include only the following information:

• A variable BeerPrice
• A method SetBeerPrice
• A method GetBeerPrice

We do not need to include any information about BeerName for example; all this is
automatically inherited. This means that FrenchBeerType has all the attributes of BeerType
plus a few additional ones. All this talk of beer...

Counters, Counters, Counters...

Back to the counter example then! The counter we had in the last section is fine for most
counting purposes. But say in a program we require a counter that can not only be
incremented, but can be decremented too. Since this new counter is so similar in behaviour to
our previous counter, once again would be mad to define a brand new class with everything
that Counter has plus a new method. Instead, we'll define a new class ReverseCounter that
is a subclass of Counter. We'll do this in Java.

class ReverseCounter extends Counter


{
public void DecrementCounter(void) {
MyCounter--;
}
}

The extends clause indicates the superclass of a class definition. A superclass is the "parent"
of a subclass; in our beer analogy, BeerType is the superclass of FrenchBeerType, so if we
were defining this in Java we would use class FrenchBeerType extends BeerType. We
are simply saying that we want ReverseCounter to be a subclass of Counter. In Java, when
we define a brand new class that is not a subclass of anything (as we did when we defined
Counter) we use the superclass Object to indicate we want the default superclass.

We have defined ReverseCounter to be a subclass of Counter. This means that if we


instantiate a ReverseCounter object, we can use any method that the class Counter
provided, as well as the new methods provided. For example, if i is an object of the
ReverseCounter class, then we can both increment it and decrement it;
i.IncrementCounter(); and i.DecrementCounter; respectively.

Inheritance is a powerful tool. Unlike our simple example, inheritance can be passed on from
generation to generation; we could define a class SuperDuperReverseCounter for example,
that is a subclass of ReverseCounter which could provide added variables or methods.

Bugs, bugs, bugs...

If you tried to compile the above example and found it wasn't compiling, don't worry! There
is a semi-deliberate mistake left in the code, which I am very usefully going to use to stress a
point.

When defining a class you must consider subclasses.

When we defined the Counter class we didn't even know what a subclass was, so we could
be forgiven for breaking this rule. If we go back to how the class was defined:
class Counter extends Object {
private int MyCounter;

...
...
}

We can see that the variable MyCounter is defined to be of type private. In Java, this means
that the variable becomes very, very private indeed; in fact, it is only accessible from inside
the class from which it is defined. It is not available to any other class, including its derived
classes. So when we reference MyCounter from inside the ReverseCounter the Java
compiler will kick up a fuss, since we don't have access to that variable.

We should have realised at the time of writing the Counter class that subclasses might need
to get at this variable too. To fix this, all we have to do is change the definition of MyCounter
to:

protected int MyCounter;

A variable with a protected qualifier means that it can be accessed from within the class in
which it is defined, as well as all subclasses of this class. This is appropriate in this case.

Next: Conclusion.

Conclusion
Congratulations if you made it this far - hopefully you found the tutorial to be of some use.
This tutorial only begins to explain OOP though - There are lots of important concepts such
as polymorphism that I just don't have time to write about! I recommend deciding on a
language to learn and obtaining any of the following books.

Programming C#
Jesse Liberty
ISBN: 0-596-00489-3
A good introduction to the C# language with a short section on Object Oriented programming
at the beginning of the text.

Accelerated C++
Andrew Koenig, Barbara Moo
ISBN: 0-201-70353-X
A great beginners guide to programming in C++.

Learning Java, 2nd Edition


Patrick Niemeyer, Jonathan Knudsen
ISBN: 0-596-00285-8
This is a book I haven't actually read (the book I learned Java from was quite dire) but it
seems like an ideal book for a beginner. Almost all of the books from O'Reilly are worth
reading.

Design Patterns, Elements of Reusable OO Software


Gamma, Helm, Johnson, Vlissides
ISBN: 0-201-63361-2
Describes Patterns, advanced Object Oriented programming solutions to common problems.
You can use this book while learning any of the above languages.
As I said at the start of this tutorial, the best way to learn OOP is by practice - pick up one of
the SDKs mentioned in the introduction and start playing today!

Please feel free to contact me with any questions on the tutorial. Good luck!

Plee support our sponsor:

Please support our sponsor:

Best New Cars


Online....!

Best New Cars


Online....!

Home Site Map Forums News Feedback

OOP:Object Oriented Programming

Name: Understanding OOP


Author: Derrick Mead
Date: 8/18/97

Description: Volumes could be written about OOP and Visual Basic. Here we skim the vital
concepts and show some code samples that may be of use as you learn.

Many thanks to Derrick for graciously providing this tutorial; check out his VBJones Web
Site.

Controls needed: N/A


Level: All

What is Object Oriented Programming?

Object Oriented Programming allows developers to mimic real world items and concepts. In
an OOP world, each object knows what information describes itself and what actions it can
perform with that information. OOP allows developers to create reusable objects that interact
with each other to form complex entities.

Definition of Classes

A "Class" is a template which defines the attributes (properties in VB) and the actions or
methods which can be performed upon those attributes for a given type of entity. The class
definition is used to create "Instances" of the class, which are the actual objects used within
your application.

A Class is generally considered to be a "Black Box". That is, you can use the object created
from a Class without knowing how the internal code works. All the developer needs to know
is which methods to call to perform certain functions. How those functions perform their
tasks is hidden.

Programmers generally create a Class for each separate entity used within their application.
Classes allow developers to write modifiable, readable, reusable code.

Objects = Attributes + Actions

An object is an "Instance" of a Class. In Visual Basic you can create any number of "Object
Variables" from a single Class Definition. Each object knows what data describes it and how
to manipluate that data.

Each data item is called an "Attribute" in OOP. Visual Basic implements these attributes as
"Properties". Properties are exposed through the Public Interface of an object. Each object
can have internal variables, not seen by users, which are used to store information the object
requires to perform its task(s).

Figure 1.2a : An Object Which Exposes Public Properties


VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsPerson"
Attribute VB_Creatable = False
Attribute VB_Exposed = False

'Internal Member Variables


Private mFirstName as String

'Public Properties

Public Property Let FirstName ( Value as String)


'assign Value to internal variable from the outside world

mFirstName = Value

End Property

Public Property Get FirstName ( ) as String


'retreive internal variable and expose to outside world

FirstName = mFirstName

End Property

Objects not only contain their own data but they know how to perform tasks on that data.
Tasks are performed by various functions and procedures defined in the Class
Definition.These functions and procedures are called Methods in OOP. Once again only those
Methods exposed by the Public Interface are available to outside users.

Figure 1.2b : An Object Which Exposes Public Methods


VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsPerson"
Attribute VB_Creatable = False
Attribute VB_Exposed = False

'Internal Member Variables


Private mFirstName as String
Private mLastName as String

'Public Properties

Public Property Let FirstName ( Value as String)


'assign Value to internal variable from the outside world

mFirstName = Value

End Property

Public Property Get FirstName ( ) as String


'retreive internal variable and expose to outside world

FirstName = mFirstName

End Property

Public Property Let LastName ( Value as String)


'assign Value to internal variable from the outside world

mLastName = Value

End Property

Public Property Get LastName ( ) as String


'retreive internal variable and expose to outside world

LastName = mLastName

End Property

'Public Methods

Public Function FullName ( ) as String


'retreives the persons full name

FullName = mFirstName & " " & mLastName

End Function

[Lesson 1 , Lesson 2]

OOP:Object Oriented Programming

Name: Understanding OOP


Author: Derrick Mead
Date: 8/18/97
Lesson: 2
Encapsulation

One of the fundamental concepts of OOP is the method with which objects store and
manipulate data known as Encapsulation.

Each object consists of internal variables which, when exposed to outside world, become its'
attributes. That is, the data that is input and output from the object. VB defines these exposed
attributes as Properties.

In addition to knowing what data to deal with, each object knows how to manipulate that
data. Functions and Procedures that perform tasks are called Methods. A Method can be used
internally or exposed to the programmer. If a Method is declared as Private then it can only
be used inside the object. The outside world does not see it.

The developer communicates and controls the object via the Public Interface, a set of Public
Properties and Methods which the object exposes to the outside. How an object performs its
tasks is of no concern to the developer using the object. It is essentially a "Black Box".

Inheritance

In the pure world of OOP, objects can be created from other objects. Any properties and
methods from one class are then automatically available as properties and methods of the new
class. This is called Inheritance.

Visual Basic provides a modified version of Inheritance commonly termed Containment. A


class can still expose its childrens' properties and methods but the developer of the class must
explicitly reference the child in any calls made to those properties or methods. A comparison
is the best way of explaining this concept.

Figure 3.1a : C++ directly uses Person.Name when Student.Name is


called.

Figure 3.1b : VB must explicitly call Person.Name when Student.Name is


called.

Let's look at how you would code this :


'Class : clsStudent
' Contains a reference to a Person Object

'private member variables


Private oPerson as clsPerson
Private iGrade as Integer

Public Sub Create ( )


'load this object and create the person object

Set oPerson = New clsPerson

End Sub

Public Property Let Name ( sNewName as String)


'set the person objects Name Property

oPerson.Name = sNewName

End Property

Public Property Get Name ( ) as String


'retreive the person objects Name Property

Name = oPerson.Name

End Property

Polymorphism

Objects can be as complex as you desire to make them. Some objects provide the
functionality of several different objects with similar behaviours. This is Polymorphism, the
ability to change the behaviour of a class based upon certain criteria.

Lets look at an example :

Two geographic areas have different methods to calculate Sales Tax.

Region A calculates Sales Tax at a flat 5% of the Sales Total.

Region B calculates Sales Tax on a prorated basis - 6% up to $200, 4% for all sales over
$200.

We can create an object class which performs the calculation for Region A, and another class
for Region B. Then create a class which references both the previous objects. When you wish
to calculate taxes just tell your Wrapper Class which region to use and the proper calculations
are performed.

Here's the code for this example :

'Class : clsTaxRegionA

Const iTaxRate = .05

Public function CalcTaxes ( curTaxableValue as Currency) as Currency

CalcTaxes = iTaxRate * curTaxableValue


End Function
'Class : clsTaxRegionB

Const iTaxRate1 = .06


Const iTaxRate2 = .04

Public function CalcTaxes ( curTaxableValue as Currency) as Currency

If curTaxValue < 200 then

CalcTaxes = iTaxRate1 * curTaxableValue

else

CalcTaxes = iTaxRate2 * curTaxableValue

end if

End Function
'Class : clsSalesTax

'private member variables


Private sRegion as String
Private oRegionA as clsTaxRegionA
Private oRegionB as clsTaxRegionB

Public Property Let Region ( sRegionFlag as String )

sRegion = sRegionFlag

End Property

Public Sub Create ( )

Set oRegionA = New clsTaxRegionA


Set oRegionB = New clsTaxRegionB

End Sub

Public function CalcTaxes ( curTaxableValue as Currency) as Currency


'calculate taxes based on region

if sRegion = "A" then

CalcTaxes = oRegionA.CalcTaxes (curTaxableValue)

else

CalcTaxes = oRegionB.CalcTaxes (curTaxableValue)

end if

End Function

[Lesson 1 , Lesson 2]
Introduction to Object Oriented
Programming Concepts (OOP) and More
• 1. Introduction
• 2. Background
• 3. Prerequisites
• 4. The Main Content
o 4.1. What is Software Architecture?
o 4.2. Why Architecture is important?
o 4.3. What is OOP?
o 4.4. What is an Object?
o 4.5. What is a Class?
o 4.6. How to identify and design a Class?
o 4.7. What is Encapsulation (or information hiding)?
o 4.8. What is Association?
o 4.9. What is the difference between Association, Aggregation and
Composition?
o 4.10. What is Abstraction and Generalization?
o 4.11. What is an Abstract class?
o 4.12. What is an Interface?
o 4.13. What is the difference between a Class and an Interface?
o 4.14. What is the difference between an Interface and an Abstract
class?
o 4.15. What is Implicit and Explicit Interface Implementations?
o 4.16. What is Inheritance?
o 4.17. What is Polymorphism?
o 4.18. What is Method Overloading?
o 4.19. What is Operator overloading?
o 4.20. What is Method Overriding?
o 4.21. What is a Use case?
o 4.22. What is a Class Diagram?
o 4.23. What is a Package Diagram?
o 4.24. What is a Sequence Diagram?
o 4.25. What is two-tier architecture?
o 4.26. What is three-tier architecture?
o 4.27. What is MVC architecture?
o 4.28. What is SOA?
o 4.29. What is the Data Access Layer?
o 4.30. What is the Business Logic Layer?
o 4.31. What is Gang of Four (GoF) Design Patterns?
o 4.32. What is the difference between Abstract Factory and Builder
design patterns?
• 5. What is the Conclusion?
• 6. What I Referred?
• 7. History

1. Introduction
I have noticed an increase in the number of articles published in the Architect
category in code-project during the last few months. The number of readers for
most of these articles is also high, though the ratings for the articles are not. This
indicates that readers are interested in reading articles on Architecture, but the
quality does not match their expectations. This article is a constructive attempt
to group/ define/ explain all introductory concepts of software architecture for
well seasoned developers who are looking to take their next step as system
architects.

One day I read an article that said that the richest 2 percent own half the world's wealth. It
also said that the richest 1 percent of adults owned 40 percent of global assets in the year
2000. And further, that the richest 10 percent of adults accounted for 85 percent of the
world's total wealth. So there is an unbalanced distribution of wealth in the physical world.
Have you ever thought of an unbalanced distribution of knowledge in the software world?
According to my view point, the massive expansion of the software industry is forcing
developers to use already implemented libraries, services and frameworks to develop
software within ever shorter periods of time. The new developers are trained to use (I would
say more often) already developed software components, to complete the development
quicker. They just plug in an existing library and some how manage to achieve the
requirements. But the sad part of the story is, that they never get a training to define, design
the architecture for, and implement such components. As the number of years pass by, these
developers become leads and also software architects. Their titles change, but the old legacy
of not understanding, of not having any architectural experience continues, creating a vacuum
of good architects. The bottom line is that only a small percentage of developers know how to
design a truly object oriented system. The solution to this problem is getting harder every day
as the aggressive nature of the software industry does not support an easy adjustment to
existing processes, and also the related online teaching materials are either complex or less
practical or sometimes even wrong. The most of them use impractical, irrelevant examples of
shapes, animals and many other physical world entities to teach concepts of software
architecture. There are only very few good business-oriented design references.
Unfortunately, I myself am no exception and am a result of this very same system. I got the
same education that all of you did, and also referred to the same resource set you all read.

Coming back to the initial point, I noticed that there is a knowledge gap, increasing every
day, between the architects who know how to architect a system properly and the others who
do not know. The ones, who know, know it right. But the ones, who do not know, know
nothing. Just like the world’s wealth distribution, it is an unbalanced distribution of
knowledge.

2. Background
This article began after reading and hearing the questions new developers have,
on basics of software architecture. There are some good articles out there, but
still developers struggle to understand the basic concepts, and more importantly,
the way to apply them correctly.

As I see it, newcomers will always struggle to understand a precise definition of a new
concept, because it is always a new and hence unfamiliar idea. The one, who has experience,
understands the meaning, but the one who doesn’t, struggles to understand the very same
definition. It is like that. Employers want experienced employees. So they say, you need to
have experience to get a job. But how the hell is one supposed to have that experience if no
one is willing to give him a job? As in the general case, the start with software architecture is
no exception. It will be difficult. When you start to design your very first system, you will try
to apply everything you know or learned from everywhere. You will feel that an interface
needs to be defined for every class, like I did once. You will find it harder to understand
when and when not to do something. Just prepare to go through a painful process. Others will
criticize you, may laugh at you and say that the way you have designed it is wrong. Listen to
them, and learn continuously. In this process you will also have to read and think a lot. I hope
that this article will give you the right start for that long journey.
“The knowledge of the actions of great men, acquired by long experience in contemporary
affairs, and a continual study of antiquity” – I read this phrase when I was reading the book
named “The Art of War”, seems applicable here, isn’t it?

3. Prerequisites
This article is an effort to provide an accurate information pool for new
developers on the basics of software architecture, focusing on Object Oriented
Programming (OOP). If you are a developer, who has a minimum of three or
more years of continuous development experience and has that hunger to learn
more, to step-in to the next level to become a software architect, this article is
for you.

4. The Main Content

4.1. What is Software Architecture?


Software Architecture is defined to be the rules, heuristics and patterns
governing:

• Partitioning the problem and the system to be built into discrete pieces
• Techniques used to create interfaces between these pieces
• Techniques used to manage overall structure and flow
• Techniques used to interface the system to its environment
• Appropriate use of development and delivery approaches, techniques and
tools.

4.2. Why Architecture is important?

The primary goal of software architecture is to define the non-functional


requirements of a system and define the environment. The detailed design is
followed by a definition of how to deliver the functional behavior within the
architectural rules. Architecture is important because it:

• Controls complexity
• Enforces best practices
• Gives consistency and uniformity
• Increases predictability
• Enables re-use.
4.3. What is OOP?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-
Oriented Programming (OOP) uses a different set of programming languages
than old procedural programming languages (C, Pascal, etc.). Everything in OOP
is grouped as self sustainable "objects". Hence, you gain re-usability by means of
four main object-oriented programming concepts.

In order to clearly understand the object orientation, let’s take your “hand” as an example.
The “hand” is a class. Your body has two objects of type hand, named left hand and right
hand. Their main functions are controlled/ managed by a set of electrical signals sent through
your shoulders (through an interface). So the shoulder is an interface which your body uses to
interact with your hands. The hand is a well architected class. The hand is being re-used to
create the left hand and the right hand by slightly changing the properties of it.

4.4. What is an Object?


An object can be considered a "thing" that can perform a set of related
activities. The set of activities that the object performs defines the object's
behavior. For example, the hand can grip something or a Student (object) can
give the name or address.

In pure OOP terms an object is an instance of a class.

4.5. What is a Class?

A class is simply a representation of a type of object. It is the blueprint/ plan/


template that describe the details of an object. A class is the blueprint from
which the individual objects are created. Class is composed of three things: a
name, attributes, and operations.

Collapse

Collapse

public class Student


{
}
According to the sample given below we can say that the student object, named
objectStudent, has created out of the Student class.

Collapse

Collapse

Student objectStudent = new Student();


In real world, you'll often find many individual objects all of the same kind. As an
example, there may be thousands of other bicycles in existence, all of the same
make and model. Each bicycle has built from the same blueprint. In object-
oriented terms, we say that the bicycle is an instance of the class of objects
known as bicycles.

In the software world, though you may not have realized it, you have already used classes.
For example, the TextBox control, you always used, is made out of the TextBox class, which
defines its appearance and capabilities. Each time you drag a TextBox control, you are
actually creating a new instance of the TextBox class.

4.6. How to identify and design a Class?

This is an art; each designer uses different techniques to identify classes. However according
to Object Oriented Design Principles, there are five principles that you must follow when
design a class,

• SRP - The Single Responsibility Principle -


A class should have one, and only one, reason to change.
• OCP - The Open Closed Principle -
You should be able to extend a classes behavior, without modifying it.
• LSP - The Liskov Substitution Principle-
Derived classes must be substitutable for their base classes.
• DIP - The Dependency Inversion Principle-
Depend on abstractions, not on concretions.
• ISP - The Interface Segregation Principle-
Make fine grained interfaces that are client specific.

For more information on design principles, please refer to Object Mentor.

Additionally to identify a class correctly, you need to identify the full list of leaf level
functions/ operations of the system (granular level use cases of the system). Then you can
proceed to group each function to form classes (classes will group same types of functions/
operations). However a well defined class must be a meaningful grouping of a set of
functions and should support the re-usability while increasing expandability/ maintainability
of the overall system.

In software world the concept of dividing and conquering is always recommended, if you
start analyzing a full system at the start, you will find it harder to manage. So the better
approach is to identify the module of the system first and then dig deep in to each module
separately to seek out classes.

A software system may consist of many classes. But in any case, when you have many, it
needs to be managed. Think of a big organization, with its work force exceeding several
thousand employees (let’s take one employee as a one class). In order to manage such a work
force, you need to have proper management policies in place. Same technique can be applies
to manage classes of your software system as well. In order to manage the classes of a
software system, and to reduce the complexity, the system designers use several techniques,
which can be grouped under four main concepts named Encapsulation, Abstraction,
Inheritance, and Polymorphism. These concepts are the four main gods of OOP world and in
software term, they are called four main Object Oriented Programming (OOP) Concepts.

4.7. What is Encapsulation (or information hiding)?


The encapsulation is the inclusion within a program object of all the resources
need for the object to function - basically, the methods and the data. In OOP the
encapsulation is mainly achieved by creating classes, the classes expose public
methods and properties. The class is kind of a container or capsule or a cell,
which encapsulate the set of methods, attribute and properties to provide its
indented functionalities to other classes. In that sense, encapsulation also allows
a class to change its internal implementation without hurting the overall
functioning of the system. That idea of encapsulation is to hide how a class does
it but to allow requesting what to do.

In order to modularize/ define the functionality of a one class, that class can uses
functions/ properties exposed by another class in many different ways. According
to Object Oriented Programming there are several techniques, classes can use to
link with each other and they are named association, aggregation, and
composition.

There are several other ways that an encapsulation can be used, as an example we can take
the usage of an interface. The interface can be used to hide the information of an
implemented class.

Collapse

Collapse

IStudent myStudent = new LocalStudent();


IStudent myStudent = new ForeignStudent();
According to the sample above (let’s assume that LocalStudent and
ForeignStudent are implemented by the IStudent interface) we can see how
LocalStudent and ForeignStudent are hiding their, localize implementing
information through the IStudent interface.

4.8. What is Association?


Association is a (*a*) relationship between two classes. It allows one object
instance to cause another to perform an action on its behalf. Association is the
more general term that define the relationship between two classes, where as
the aggregation and composition are relatively special.

Collapse

Collapse

public class StudentRegistrar


{
public StudentRegistrar ();
{
new RecordManager().Initialize();
}
}
In this case we can say that there is an association between StudentRegistrar
and RecordManager or there is a directional association from StudentRegistrar to
RecordManager or StudentRegistrar use a (*Use*) RecordManager. Since a
direction is explicitly specified, in this case the controller class is the
StudentRegistrar.

To some beginners, association is a confusing concept. The troubles created not


only by the association alone, but with two other OOP concepts, that is
association, aggregation and composition. Every one understands association,
before aggregation and composition are described. The aggregation or
composition cannot be separately understood. If you understand the aggregation
alone it will crack the definition given for association, and if you try to
understand the composition alone it will always threaten the definition given for
aggregation, all three concepts are closely related, hence must study together,
by comparing one definition to another. Let’s explore all three and see whether
we can understand the differences between these useful concepts.

4.9. What is the difference between Association,


Aggregation and Composition?
Association is a (*a*) relationship between two classes, where one class use
another. But aggregation describes a special type of an association. Aggregation
is the (*the*) relationship between two classes. When object of one class has an
(*has*) object of another, if second is a part of first (containment relationship)
then we called that there is an aggregation between two classes. Unlike
association, aggregation always insists a direction.

Collapse

Collapse

public class University


{
private Chancellor universityChancellor = new Chancellor();
}

In this case I can say that University aggregate Chancellor or University has an
(*has-a*) Chancellor. But even without a Chancellor a University can exists. But
the Faculties cannot exist without the University, the life time of a Faculty (or
Faculties) attached with the life time of the University . If University is disposed
the Faculties will not exist. In that case we called that University is composed of
Faculties. So that composition can be recognized as a special type of an
aggregation.
Same way, as another example, you can say that, there is a composite relationship in-between
a KeyValuePairCollection and a KeyValuePair. The two mutually depend on each other.

.Net and Java uses the Composite relation to define their Collections. I have seen
Composition is being used in many other ways too. However the more important factor, that
most people forget is the life time factor. The life time of the two classes that has bond with a
composite relation mutually depend on each other. If you take the .net Collection to
understand this, there you have the Collection Element define inside (it is an inner part, hence
called it is composed of) the Collection, farcing the Element to get disposed with the
Collection. If not, as an example, if you define the Collection and it’s Element to be
independent, then the relationship would be more of a type Aggregation, than a Composition.
So the point is, if you want to bind two classes with Composite relation, more accurate way is
to have a one define inside the other class (making it a protected or private class). This way
you are allowing the outer class to fulfill its purpose, while tying the lifetime of the inner
class with the outer class.

So in summary, we can say that aggregation is a special kind of an association and


composition is a special kind of an aggregation. (Association->Aggregation->Composition)

4.10. What is Abstraction and Generalization?


Abstraction is an emphasis on the idea, qualities and properties rather than the
particulars (a suppression of detail). The importance of abstraction is derived
from its ability to hide irrelevant details and from the use of names to reference
objects. Abstraction is essential in the construction of programs. It places the
emphasis on what an object is or does rather than how it is represented or how it
works. Thus, it is the primary means of managing complexity in large programs.

While abstraction reduces complexity by hiding irrelevant detail, generalization reduces


complexity by replacing multiple entities which perform similar functions with a single
construct. Generalization is the broadening of application to encompass a larger domain of
objects of the same or different type. Programming languages provide generalization through
variables, parameterization, generics and polymorphism. It places the emphasis on the
similarities between objects. Thus, it helps to manage complexity by collecting individuals
into groups and providing a representative which can be used to specify any individual of the
group.

Abstraction and generalization are often used together. Abstracts are generalized through
parameterization to provide greater utility. In parameterization, one or more parts of an entity
are replaced with a name which is new to the entity. The name is used as a parameter. When
the parameterized abstract is invoked, it is invoked with a binding of the parameter to an
argument.

4.11. What is an Abstract class?


Abstract classes, which declared with the abstract keyword, cannot be
instantiated. It can only be used as a super-class for other classes that extend
the abstract class. Abstract class is the concept and implementation gets
completed when it is being realized by a subclass. In addition to this a class can
inherit only from one abstract class (but a class may implement many interfaces)
and must override all its abstract methods/ properties and may override virtual
methods/ properties.

Abstract classes are ideal when implementing frameworks. As an example, let’s study the
abstract class named LoggerBase below. Please carefully read the comments as it will help
you to understand the reasoning behind this code.

Collapse

Collapse

public abstract class LoggerBase


{
/// <summary>
/// field is private, so it intend to use inside the class only
/// </summary>
private log4net.ILog logger = null;

/// <summary>
/// protected, so it only visible for inherited class
/// </summary>
protected LoggerBase()
{
// The private object is created inside the constructor
logger = log4net.LogManager.GetLogger(this.LogPrefix);
// The additional initialization is done immediately after
log4net.Config.DOMConfigurator.Configure();
}

/// <summary>
/// When you define the property as abstract,
/// it forces the inherited class to override the LogPrefix
/// So, with the help of this technique the log can be made,
/// inside the abstract class itself, irrespective of it origin.
/// If you study carefully you will find a reason for not to have “set”
method here.
/// </summary>
protected abstract System.Type LogPrefix
{
get;
}

/// <summary>
/// Simple log method,
/// which is only visible for inherited classes
/// </summary>
/// <param name="message"></param>
protected void LogError(string message)
{
if (this.logger.IsErrorEnabled)
{
this.logger.Error(message);
}
}

/// <summary>
/// Public properties which exposes to inherited class
/// and all other classes that have access to inherited class
/// </summary>
public bool IsThisLogError
{
get
{
return this.logger.IsErrorEnabled;
}
}
}
The idea of having this class as an abstract is to define a framework for
exception logging. This class will allow all subclass to gain access to a common
exception logging module and will facilitate to easily replace the logging library.
By the time you define the LoggerBase, you wouldn’t have an idea about other
modules of the system. But you do have a concept in mind and that is, if a class
is going to log an exception, they have to inherit the LoggerBase. In other word
the LoggerBase provide a framework for exception logging.

Let’s try to understand each line of the above code.

Like any other class, an abstract class can contain fields, hence I used a private field named
logger declare the ILog interface of the famous log4net library. This will allow the
Loggerbase class to control, what to use, for logging, hence, will allow changing the source
logger library easily.

The access modifier of the constructor of the LoggerBase is protected. The public constructor
has no use when the class is of type abstract. The abstract classes are not allowed to
instantiate the class. So I went for the protected constructor.

The abstract property named LogPrefix is an important one. It enforces and guarantees to
have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the
exception has occurred) for every subclass, before they invoke a method to log an error.

The method named LogError is protected, hence exposed to all subclasses. You are not
allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase
cannot use it meaningfully.

Let’s find out why the property named IsThisLogError is public. It may be important/ useful
for other associated classes of an inherited class to know whether the associated member logs
its errors or not.

Apart from these you can also have virtual methods defined in an abstract class. The virtual
method may have its default implementation, where a subclass can override it when required.
All and all, the important factor here is that all OOP concepts should be used carefully with
reasons, you should be able to logically explain, why you make a property a public or a field
a private or a class an abstract. Additionally, when architecting frameworks, the OOP
concepts can be used to forcefully guide the system to be developed in the way framework
architect’s wanted it to be architected initially.

4.12. What is an Interface?


In summary the Interface separates the implementation and defines the
structure, and this concept is very useful in cases where you need the
implementation to be interchangeable. Apart from that an interface is very useful
when the implementation changes frequently. Some say you should define all
classes in terms of interfaces, but I think recommendation seems a bit extreme.

Interface can be used to define a generic template and then one or more abstract classes to
define partial implementations of the interface. Interfaces just specify the method declaration
(implicitly public and abstract) and can contain properties (which are also implicitly public
and abstract). Interface definition begins with the keyword interface. An interface like that of
an abstract class cannot be instantiated.

If a class that implements an interface does not define all the methods of the interface, then it
must be declared abstract and the method definitions must be provided by the subclass that
extends the abstract class. In addition to this an interfaces can inherit other interfaces.

The sample below will provide an interface for our LoggerBase abstract class.

Collapse

Collapse

public interface ILogger


{
bool IsThisLogError { get; }
}

4.13. What is the difference between a Class and an


Interface?
In .Net/ C# a class can be defined to implement an interface and also it supports
multiple implementations. When a class implements an interface, an object of
such class can be encapsulated inside an interface.

If MyLogger is a class, which implements ILogger, there we can write

Collapse

Collapse

ILogger log = new MyLogger();


A class and an interface are two different types (conceptually). Theoretically a
class emphasis the idea of encapsulation, while an interface emphasis the idea
of abstraction (by suppressing the details of the implementation). The two poses
a clear separation from one to another. Therefore it is very difficult or rather
impossible to have an effective meaningful comparison between the two, but it is
very useful and also meaningful to have a comparison between an interface and
an abstract class.

4.14. What is the difference between an Interface and


an Abstract class?

There are quite a big difference between an interface and an abstract class, even though both
look similar.

o Interface definition begins with a keyword interface so it is of type


interface
o Abstract classes are declared with the abstract keyword so it is of
type class
o Interface has no implementation, but they have to be implemented.
o Abstract class’s methods can have implementations and they have
to be extended.
o Interfaces can only have method declaration (implicitly public and
abstract) and fields (implicitly public static)
o Abstract class’s methods can’t have implementation only when
declared abstract.
o Interface can inherit more than one interfaces
o Abstract class can implement more than one interfaces, but can
inherit only one class
o Abstract class must override all abstract method and may override
virtual methods
o Interface can be used when the implementation is changing
o Abstract class can be used to provide some default behavior for a
base class.
o Interface makes implementation interchangeable
o Interface increase security by hiding the implementation
o Abstract class can be used when implementing framework
o Abstract classes are an excellent way to create planned inheritance
hierarchies and also to use as non-leaf classes in class hierarchies.

Abstract classes let you define some behaviors; they force your subclasses to provide others.
For example, if you have an application framework, an abstract class can be used to provide
the default implementation of the services and all mandatory modules such as event logging
and message handling etc. This approach allows the developers to develop the application
within the guided help provided by the framework.

However, in practice when you come across with some application-specific functionality that
only your application can perform, such as startup and shutdown tasks etc. The abstract base
class can declare virtual shutdown and startup methods. The base class knows that it needs
those methods, but an abstract class lets your class admit that it doesn't know how to perform
those actions; it only knows that it must initiate the actions. When it is time to start up, the
abstract class can call the startup method. When the base class calls this method, it can
execute the method defined by the child class.

4.15. What is Implicit and Explicit Interface


Implementations?

As mentioned before .Net support multiple implementations, the concept of implicit and
explicit implementation provide safe way to implement methods of multiple interfaces by
hiding, exposing or preserving identities of each of interface methods, even when the method
signatures are the same.

Let's consider the interfaces defined below.

Collapse

Collapse

interface IDisposable
{
void Dispose();
}

Here you can see that the class Student has implicitly and explicitly implemented the method
named Dispose() via Dispose and IDisposable.Dispose.

Collapse

Collapse

class Student : IDisposable


{
public void Dispose()
{
Console.WriteLine("Student.Dispose");
}

void IDisposable.Dispose()
{
Console.WriteLine("IDisposable.Dispose");
}
}

4.16. What is Inheritance?

Ability of a new class to be created, from an existing class by extending it, is called
inheritance.

Collapse

Collapse

public class Exception


{
}
public class IOException : Exception
{
}

According to the above example the new class (IOException), which is called the derived
class or subclass, inherits the members of an existing class (Exception), which is called the
base class or super-class. The class IOException can extend the functionality of the class
Exception by adding new types and methods and by overriding existing ones.

Just like abstraction is closely related with generalization, the inheritance is closely related
with specialization. It is important to discuss those two concepts together with generalization
to better understand and to reduce the complexity.

One of the most important relationships among objects in the real world is specialization,
which can be described as the “is-a” relationship. When we say that a dog is a mammal, we
mean that the dog is a specialized kind of mammal. It has all the characteristics of any
mammal (it bears live young, nurses with milk, has hair), but it specializes these
characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As
such, we expect it to share certain characteristics with the dog that are generalized in
Mammal, but to differ in those characteristics that are specialized in cats.

The specialization and generalization relationships are both reciprocal and hierarchical.
Specialization is just the other side of the generalization coin: Mammal generalizes what is
common between dogs and cats, and dogs and cats specialize mammals to their own specific
subtypes.

Similarly, as an example you can say that both IOException and SecurityException are of
type Exception. They have all characteristics and behaviors of an Exception, That mean the
IOException is a specialized kind of Exception. A SecurityException is also an Exception. As
such, we expect it to share certain characteristic with IOException that are generalized in
Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In
other words, Exception generalizes the shared characteristics of both IOException and
SecurityException, while IOException and SecurityException specialize with their
characteristics and behaviors.

In OOP, the specialization relationship is implemented using the principle called inheritance.
This is the most common and most natural and widely accepted way of implement this
relationship.

4.17. What is Polymorphisms?


Polymorphisms is a generic term that means 'many shapes'. More precisely
Polymorphisms means the ability to request that the same operations be
performed by a wide range of different types of things.

At times, I used to think that understanding Object Oriented Programming concepts have
made it difficult since they have grouped under four main concepts, while each concept is
closely related with one another. Hence one has to be extremely careful to correctly
understand each concept separately, while understanding the way each related with other
concepts.

In OOP the polymorphisms is achieved by using many different techniques named method
overloading, operator overloading and method overriding,
4.18. What is Method Overloading?
The method overloading is the ability to define several methods all with the
same name.

Collapse

Collapse

public class MyLogger


{
public void LogError(Exception e)
{
// Implementation goes here
}

public bool LogError(Exception e, string message)


{
// Implementation goes here
}
}

4.19. What is Operator Overloading?


The operator overloading (less commonly known as ad-hoc polymorphisms) is a
specific case of polymorphisms in which some or all of operators like +, - or ==
are treated as polymorphic functions and as such have different behaviors
depending on the types of its arguments.

Collapse

Collapse

public class Complex


{
private int real;
public int Real
{ get { return real; } }

private int imaginary;


public int Imaginary
{ get { return imaginary; } }

public Complex(int real, int imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)


{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}
I above example I have overloaded the plus operator for adding two complex
numbers. There the two properties named Real and Imaginary has been declared
exposing only the required “get” method, while the object’s constructor is
demanding for mandatory real and imaginary values with the user defined
constructor of the class.
4.20. What is Method Overriding?
Method overriding is a language feature that allows a subclass to override a
specific implementation of a method that is already provided by one of its super-
classes.

A subclass can give its own definition of methods but need to have the same signature as the
method in its super-class. This means that when overriding a method the subclass's method
has to have the same name and parameter list as the super-class's overridden method.

Collapse

Collapse

using System;
public class Complex
{
private int real;
public int Real
{ get { return real; } }

private int imaginary;


public int Imaginary
{ get { return imaginary; } }

public Complex(int real, int imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)


{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}

public override string ToString()


{
return (String.Format("{0} + {1}i", real, imaginary));
}
}
In above example I have extended the implementation of the sample Complex
class given under operator overloading section. This class has one overridden
method named “ToString”, which override the default implementation of the
standard “ToString” method to support the correct string conversion of a
complex number.

Collapse

Collapse

Complex num1 = new Complex(5, 7);


Complex num2 = new Complex(3, 8);

// Add two Complex numbers using the


// overloaded plus operator
Complex sum = num1 + num2;

// Print the numbers and the sum


// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();
4.21. What is a Use case?

A use case is a thing an actor perceives from the system. A use case maps actors with
functions. Importantly, the actors need not be people. As an example a system can perform
the role of an actor, when it communicate with another system.

In another angle a use case encodes a typical user interaction with the system.
In particular, it:

• Captures some user-visible function.

• Achieves some concrete goal for the user.

A complete set of use cases largely defines the requirements for your system:
everything the user can see, and would like to do. The below diagram contains a
set of use cases that describes a simple login module of a gaming website.

4.22. What is a Class Diagram?

A class diagrams are widely used to describe the types of objects in a system and their
relationships. Class diagrams model class structure and contents using design elements such
as classes, packages and objects. Class diagrams describe three different perspectives when
designing a system, conceptual, specification, and implementation. These perspectives
become evident as the diagram is created and help solidify the design.

The Class diagrams, physical data models, along with the system overview diagram are in my
opinion the most important diagrams that suite the current day rapid application development
requirements.

UML Notations:
4.23. What is a Package Diagram?
Package diagrams are used to reflect the organization of packages and their
elements. When used to represent class elements, package diagrams provide a
visualization of the name-spaces. In my designs, I use the package diagrams to
organize classes in to different modules of the system.

4.24. What is a Sequence Diagram?


A sequence diagrams model the flow of logic within a system in a visual manner,
it enable both to document and validate your logic, and are used for both
analysis and design purposes. Sequence diagrams are the most popular UML
artifact for dynamic modeling, which focuses on identifying the behavior within
your system.

4.25. What is two-tier architecture?


The two-tier architecture is refers to client/ server architectures as well, the term
client/ server was first used in the 1980s in reference to personal computers
(PCs) on a network. The actual client/ server model started gaining acceptance in
the late 1980s, and later it was adapted to World Wide Web programming.

According to the modern days use of two-tier architecture the user interfaces (or with
ASP.NET, all web pages) runs on the client and the database is stored on the server. The
actual application logic can run on either the client or the server. So in this case the user
interfaces are directly access the database. Those can also be non-interface processing
engines, which provide solutions to other remote/ local systems. In either case, today the two-
tier model is not as reputed as the three-tier model. The advantage of the two-tier design is its
simplicity, but the simplicity comes with the cost of scalability. The newer three-tier
architecture, which is more famous, introduces a middle tier for the application logic.

4.26. What is three-tier architecture?


The three tier software architecture (also known as three layer architectures)
emerged in the 1990s to overcome the limitations of the two tier architecture.
This architecture has aggressively customized and adopted by modern day
system designer to web systems.

Three-tier is a client-server architecture in which the user interface, functional process logic,
data storage and data access are developed and maintained as independent modules, some
time on separate platforms. The term "three-tier" or "three-layer", as well as the concept of
multi-tier architectures (often refers to as three-tier architecture), seems to have originated
within Rational Software.

The 3-Tier architecture has the following three tiers.

1. Presentation Tier or Web Server: User Interface, displaying/ accepting


data/ input to/ from the user
2. Application Logic/ Business Logic/ Transaction Tier or Application
Server: Data validation, acceptability check before being added to the
database and all other business/ application specific operations
3. Data Tier or Database server: Simple reading and writing method to
database or any other storage, connection, command, stored procedures
etc

4.27. What is MVC architecture?


The Model-View-Controller (MVC) architecture separates the modeling of the
domain, the presentation, and the actions based on user input into three
separate classes.

Unfortunately, the popularity of this pattern has resulted in a number of faulty usages; each
technology (Java, ASP.NET etc) has defined it in their own way making it difficult to
understand. In particular, the term "controller" has been used to mean different things in
different contexts. The definitions given bellow are the closes possible ones I found for
ASP.NET version of MVC.
1. Model: DataSet and typed DataSet (some times business object, object
collection, XML etc) are the most common use of the model.
2. View: The ASPX and ASCX files generally handle the responsibilities of the
view.
3. Controllers: The handling of events or the controlling is usually done in
the code-behind class.

In a complex n-tier distributed system the MVC architecture place the vital role of
organizing the presentation tier of the system.

4.28. What is SOA?


A service-oriented architecture is essentially a collection of services. These
services communicate with each other. The communication can involve either
simple data passing or it could involve two or more services coordinating some
activity. Some means of connecting services to each other is needed.

The .Net technology introduces the SOA by mean of web services.


The SOA can be used as the concept to connect multiple systems to provide services. It has
it's great share in the future of the IT world.

According to the imaginary diagram above, we can see how the Service Oriented
Architecture is being used to provide a set of centralized services to the citizens of a country.
The citizens are given a unique identifying card, where that card carries all personal
information of each citizen. Each service centers such as shopping complex, hospital, station,
and factory are equipped with a computer system where that system is connected to a central
server, which is responsible of providing service to a city. As an example when a customer
enter the shopping complex the regional computer system report it to the central server and
obtain information about the customer before providing access to the premises. The system
welcomes the customer. The customer finished the shopping and then by the time he leaves
the shopping complex, he will be asked to go through a billing process, where the regional
computer system will manage the process. The payment will be automatically handled with
the input details obtain from the customer identifying card.

The regional system will report to the city (computer system of the city) while the city will
report to the country (computer system of the country).

4.29. What is the Data Access Layer?


The data access layer (DAL), which is a key part of every n-tier system, is mainly
consist of a simple set of code that does basic interactions with the database or
any other storage device. These functionalities are often referred to as CRUD
(Create, Retrieve, Update, and Delete).

The data access layer need to be generic, simple, quick and efficient as much as possible. It
should not include complex application/ business logics.

I have seen systems with lengthy, complex store procedures (SP), which run through several
cases before doing a simple retrieval. They contain not only most part of the business logic,
but application logic and user interface logic as well. If SP is getting longer and complicated,
then it is a good indication that you are burring your business logic inside the data access
layer.

4.30. What is the Business Logic Layer?


I know for a fact that this is a question for most, but from the other hand by
reading many articles I have become aware that not everyone agrees to what
business logic actually is, and in many cases it's just the bridge in between the
presentation layer and the data access layer with having nothing much, except
taking from one and passing to the other. In some other cases, it is not even
been well thought out, they just take the leftovers from the presentation layer
and the data access layer then put them in another layer which automatically is
called the business logic layer. However there are no god said things that cannot
be changed in software world. You can change as and when you feel comfortable
that the method you apply is flexible enough to support the growth of your
system. There are many great ways, but be careful when selecting them, they
can over complicating the simple system. It is a balance one needs to find with
their experience.

As a general advice when you define business entities, you must decide how to map the data
in your tables to correctly defined business entities. The business entities should
meaningfully define considering various types of requirements and functioning of your
system. It is recommended to identify the business entities to encapsulate the functional/ UI
(User Interface) requirements of your application, rather than define a separate business
entity for each table of your database. For example, if you want to combine data from couple
of table to build a UI (User Interface) control (Web Control), implement that function in the
Business Logic Layer with a business object that uses couple of data object to support with
your complex business requirement.
4.31. What is Gang of Four (GoF) Design Patterns?
The Gang of Four (GoF) patterns are generally considered the foundation for all
other patterns. They are categorized in three groups: Creational, Structural, and
Behavioral. Here you will find information on these important patterns.

Creational Patterns

o Abstract Factory Creates an instance of several families of classes


o Builder Separates object construction from its representation
o Factory Method Creates an instance of several derived classes
o Prototype A fully initialized instance to be copied or cloned
o Singleton A class of which only a single instance can exist

Structural Patterns

o Adapter Match interfaces of different classes


o Bridge Separates an object’s interface from its implementation
o Composite A tree structure of simple and composite objects
o Decorator Add responsibilities to objects dynamically
o Facade A single class that represents an entire subsystem
o Flyweight A fine-grained instance used for efficient sharing
o Proxy An object representing another object

Behavioral Patterns

o Chain of Resp. A way of passing a request between a chain of


objects
o Command Encapsulate a command request as an object
o Interpreter A way to include language elements in a program
o Iterator Sequentially access the elements of a collection
o Mediator Defines simplified communication between classes
o Memento Capture and restore an object's internal state
o Observer A way of notifying change to a number of classes
o State Alter an object's behavior when its state changes
o Strategy Encapsulates an algorithm inside a class
o Template Method Defer the exact steps of an algorithm to a
subclass
o Visitor Defines a new operation to a class without change

4.32. What is the difference between Abstract Factory


and Builder design patterns?

The two design patterns are fundamentally different. However, when you learn them for the
first time, you will see a confusing similarity. So that it will make harder for you to
understand them. But if you continue to study eventually, you will get afraid of design
patterns too. It is like infant phobia, once you get afraid at your early age, it stays with you
forever. So the result would be that you never look back at design patterns again. Let me see
whether I can solve this brain teaser for you.

In the image below, you have both design pattern listed in. I am trying to compare the two
one on one to identify the similarities. If you observe the figure carefully, you will see an
easily understandable color pattern (same color is used to mark the classes that are of similar
kind).
Please follow up with the numbers in the image when reading the listing below.

Mark #1: Both patterns have used a generic class as the entry-class. The only difference is the
name of the class. One pattern has named it as “Client”, while the other named it as
“Director”.
Mark #2: Here again the difference is the class name. It is “AbstractFactory” for one and
“Builder” for the other. Additionally both classes are of type abstract.
Mark #3: Once again both patterns have defined two generic (WindowsFactory &
ConcreteBuilder) classes. They both have created by inheriting their respective abstract class.

Mark #4: Finally, both seem to produce some kind of a generic output.

Now, where are we? Aren’t they looking almost identical? So then why are we having two
different patterns here?

Let’s compare the two again side by side for one last time, but this time, focusing on the
differences.

• Abstract Factory: Emphasizes a family of product objects (either simple or


complex)
• Builder: Focuses on constructing a complex object step by step

• Abstract Factory: Focus on *what* is made


• Builder: Focus on *how* it is made
• Abstract Factory: Focus on defining many different types of *factories* to
build many *products*, and it is not a one builder for just one product
• Builder: Focus on building a one complex but one single *product*

• Abstract Factory: Defers the choice of what concrete type of object to


make until run time
• Builder: Hide the logic/ operation of how to compile that complex object

• Abstract Factory: *Every* method call creates and returns different objects
• Builder: Only the *last* method call returns the object, while other calls
partially build the object

Sometimes creational patterns are complementary: So you can join one or many patterns
when you design your system. As an example builder can use one of the other patterns to
implement which components get built or in another case Abstract Factory, Builder, and
Prototype can use Singleton in their implementations. So the conclusion would be that the
two design patterns exist to resolve two type of business problems, so even though they look
similar, they are not.

I hope that this shed some light to resolve the puzzle. If you still don’t understand it, then this
time it is not you, it has to be me and it is since that I don’t know how to explain it.

5. What is the Conclusion?

I don't think, that it is realistic trying to make a programming language be everything to


everybody. The language becomes bloated, hard to learn, and hard to read if everything plus
the kitchen sink is thrown in. In another word every language has their limitations. As system
architect and designer we should be able to fully and more importantly correctly (this also
mean that you shouldn’t use a ballistic missile to kill a fly or hire FBI to catch the fly) utilize
the available tools and features to build usable, sustainable, maintainable and also very
importantly expandable software systems, that fully utilize the feature of the language to
bring a competitively advance system to their customers. In order to do it, the foundation of a
system places a vital role. The design or the architecture of a software system is the
foundation. It hold the system together, hence designing a system properly (this never mean
an *over* desinging) is the key to the success. When you talk about designing a software
system, the correct handling of OOP concept is very important. I have made the above article
richer with idea but still kept it short so that one can learn/ remind all of important concept at
a glance. Hope you all will enjoy reading it.

Finally, after reading all these, one may argue with me saying that anybody can write all
these concept definitions but do I know how/ when to apply them in real world systems. So
for them to see these concepts being applied in real world systems, please check the source
code of the latest of my open-source project name Rocket Framework.

Note: For newbies Rocket Framework is going to be little too advance but check it, use it and
review it if you have any questions/ criticisms around my design don't hesitate to shoot them
here or there..

6. What I Referred?

• MSDN Library: http://msdn2.microsoft.com/en-us/library/default.aspx


• Practical Approach to Computer Systems Design and Architecture:
http://www.codeproject.com/useritems/System_Design.asp
• Introduction: What is Object-Oriented Programming?:
http://www.inf.ufsc.br/poo/smalltalk/ibm/tutorial/oop.html
• Basic Object-Oriented Concepts:
http://www.toa.com/pub/oobasics/oobasics.htm
• Inheritance and Polymorphism—Specialization and Generalization:
http://en.csharp-online.net/Inheritance_and_Polymorphism
%E2%80%94Specialization_and_Generalization
• Abstraction and Generalization:
http://cs.wwc.edu/~aabyan/PLBook/HTML/AbsGen.html
• Object Oriented Analysis and Design Team:
http://atlas.kennesaw.edu/~dbraun/csis4650/A&D/index.htm
• Client/Server Software Architectures--An Overview:
http://www.sei.cmu.edu/str/descriptions/clientserver.html
• Service-oriented architecture (SOA) definition: http://www.service-
architecture.com/web-services/articles/service-
oriented_architecture_soa_definition.html
• http://www.dofactory.com/Patterns/Patterns.aspx
• http://www.objectmentor.com
• Builder Design Pattern [Wiki]

7. History

• 28/01/2008
o - Added more content base on design principles.
o - Added History section
• 04/02/2008
o - Added more details to explain the Composition.
• 15/04/2008
o - Added Comparison between Abstract Factory and Builder
o - Updated some of the wording slightly
• 31/05/2010
o - Corrected the 'Composition' related description, as pointed here
• 26/01/2011
o Conclusion is updated and a link is added to Rocket-Framework

License

This article, along with any associated source code and files, is licensed under The Code
Project Open License (CPOL)
Object Oriented Programming for VB.NET - Part 1
by Budi Kurniawan
09/25/2001

If you ask an OOP guru what an OOP language is, you will probably hear him/her utter
words such as class, interface, information hiding, encapsulation, inheritance, polymorphism,
etc. Those sound cool, don't they? OOP, however, is a topic that is not too easy to master in a
day or two or by just attending a lecture. To truly understand it, you need to know the theory
as well as do some OOP coding practice. This article offers readers just getting into OOP the
very basics of OOP, using VB.NET as the language. It is not a complete reference, but it is
something to start with.

The Benefits of OOP

Have you wondered why modern programming languages tend to be object-oriented? C++
was created as an extension of C to support OOP. And Java, one of the most popular
languages on the planet, is also an OOP language. Then, of course, VisualBasic has evolved
into VB.NET, a fully OOP language. There is a good reason for this transformation. OOP
offers several benefits, such as easy code maintenance, extensibility, and code reuse, not
found in procedural programming languages. Some of the benefits are outlined below.

• Easy Maintenance. Modularity is inherent in OOP. Entities are


represented by classes and classes with the same functionality are located
in the same namespace (package). You can add a class into a namespace
without affecting other members of the namespace.
• Extensibility. OOP naturally supports extensibility. Having a class with
certain functionality, you can quickly extend that class to create a
different class with extended functionality.
• Code Reuse. Since functionality is encapsulated into a class and each
class is an independent entity, providing a library is very easy. In fact,
programmers of any .NET Framework language can and should use the
.NET Framework class library, an extensive library that provides rich
functionality. Better still, you can extend the functionality of the class
library to provide classes that suit your needs.

OOP Features

Now, let's look at some of the features of OOP, starting with the easiest one, classes.

Classes

Classes are the main focus in OOP. Simply put, a class is a data type that provides some
functionality. A class in VB.NET is declared using the keyword Class. For example, Listing
1 presents a class called Employee.

Listing 1: Class Employee

Class Employee
End Class

As simple as that. Note that Microsoft recommends the use of Pascal-case naming for classes.
This means the first character of a class name is uppercase, and so is the first letter of any
subsequent concatenated words. Good class names according to this convention include
GeneralManager, SmallDictionary, StringUtil, and so on.

Class Members

A class can have members such as fields, properties and subroutines and functions. For
example, Listing 2 presents the Employee class with a subroutine called Work.

Listing 2: Class Employee with method Work

Class Employee
Public Sub Work ()
' Do something here
End Sub
End Class

Subroutines and functions are both called methods. Method names are also Pascal-case.
Another type of class member is a field. A field name is camel-case, which means you
capitalize the first character of each word except the initial character. Examples of good field
names are salary, quarterlyBonus, etc. Adding two fields called salary and yearlyBonus
to the Employee class in Listing 2 will result in the following code.

Listing 3: Class Employee with two fields

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
System.Console.Write(salary)
End Sub

End Class

Instantiating an Object

A class is a template or a blueprint of the entity that the class represents. To use a class's field
or method or any other member, you need to first turn the class into an object, just as the
blueprint of a sports car is useless until assembly workers make the car. In other words, you
drive a car, not the blueprint of a car.

In OOP, an object is said to be an instance of a class. Creating an object is therefore known as


instantiation. The code in Listing 4 demonstrates the instantiation of the Employee class.

Listing 4: Instantiating an object

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
System.Console.Write(salary)
End Sub

End Class

Module Module1
Public Sub Main()

Dim anEmployee As Employee


anEmployee = New Employee()
anEmployee.PrintSalary()

End Sub
End Module

The module Module1 in Listing 4 provides the Main sub, which is the entry point of a
VB.NET program. In order to compile, a source file must provide access to the Main sub in
one way or another. If you are not using Visual Studio.NET, you can compile your VB.NET
program with vbc.exe, which is automatically installed when you install the .NET
Framework. For instance, if you save your source code as Employee.vb, go to the directory
where the file Employee.vb is stored, and then type vbc Employee.vb.

Now back to the code. The Main sub first declares an object variable of type Employee. The
variable is called anEmployee.

Dim anEmployee As Employee

It then instantiates Employee with the keyword New.

anEmployee = New Employee()

Now that you have an object of type Employee, you can use its functionality. (Once the car is
built, you can start and drive it.) In our example, we can call the PrintSalary method as
follows.

anEmployee.PrintSalary()

This will print the value of the salary variable in Employee.

You can also move the Main sub into the class. This way, you don't need a module. This
approach is shown in Listing 5.

Pages: 1, 2, 3 Next Page

Listing 5: Moving the Main sub to the class itself

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
System.Console.Write(salary)
End Sub
Public Shared Sub Main()

Dim employee As Employee


employee = New Employee()
employee.PrintSalary()

End Sub

End Class

Note that System.Console.Write in the PrintSalary method means that you call the
Write method of the Console class. Console is part of the System namespace. Namespaces
are discussed next.

Namespaces

When you write a .NET program, you write classes and other types. To make your
application more organized, you can group your classes into namespaces. This is also what
Microsoft does with the .NET Framework class library. If you open the .NET Framework
class library in the .NET Framework SDK documentation, you can see there are more than 80
namespaces. Important namespaces you will frequently use include System, System.IO,
System.Drawing, System.Windows.Forms, etc.

For example, in the PrintSalary method in the Employee class we used the Console class
in the System namespace.

If you will be using a namespace often, you can import a namespace so that you don't have to
repeat it every time you want to use its member. For instance, you can rewrite the code in
Listings 4 and 5 as shown below.

Listing 6: Importing a namespace

Imports System

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
Console.Write(salary)
End Sub

Public Shared Sub Main()


Dim employee As Employee
employee = New Employee()
employee.PrintSalary()
End Sub

End Class
Now, you can use the Console class in the PrintSalary method without mentioning the
namespace because the namespace is already imported. Namespaces also allow you to have
classes with the same name in different namespaces. To refer to a class correctly, it is
common practice to mention the namespace in front of the class name. For example, the
Console class in the System namespace is referred to as System.Console.

Access Types

In many cases, when you write a class, you will provide that class to other people so they can
use its functionality, i.e., they can call methods of that class or access its fields. One of the
great benefits of OOP is that you can restrict access to a class member. This means, you have
full control over what you want to expose. You can write methods that can be called by other
programmers, or you can have methods that are not accessible by anyone other than from
inside the class itself.

VB.NET offers levels of accessibility, as follows:

• Public. Public class members don't have access restrictions. You use the keyword
Public in front of the class member to make it available publicly. For example, the
PrintSalary method in the Employee class is a public method. It can be called from
anywhere.
• Private. Private class member can only be accessed from inside the class itself. Use
the Private keyword to make a class member private.
• Protected. A protected member is accessible to a derived class and from inside the
class itself. Use the Protected keyword to make a member protected.
• Friend. Members with the friend access restriction are accessible only within the
program that contains the class declaration. Use the keyword Friend to make a
member have friend restriction.
• Protected friend. This is the union of protected and friend.

These different access types provide for information hiding in OOP. In other words, you can
protect class members that you don't want to expose.

Pages: 1, 2, 3

Next Page

Listing 5: Moving the Main sub to the class itself

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
System.Console.Write(salary)
End Sub

Public Shared Sub Main()

Dim employee As Employee


employee = New Employee()
employee.PrintSalary()
End Sub

End Class

Note that System.Console.Write in the PrintSalary method means that you call the
Write method of the Console class. Console is part of the System namespace. Namespaces
are discussed next.

Namespaces

When you write a .NET program, you write classes and other types. To make your
application more organized, you can group your classes into namespaces. This is also what
Microsoft does with the .NET Framework class library. If you open the .NET Framework
class library in the .NET Framework SDK documentation, you can see there are more than 80
namespaces. Important namespaces you will frequently use include System, System.IO,
System.Drawing, System.Windows.Forms, etc.

For example, in the PrintSalary method in the Employee class we used the Console class
in the System namespace.

If you will be using a namespace often, you can import a namespace so that you don't have to
repeat it every time you want to use its member. For instance, you can rewrite the code in
Listings 4 and 5 as shown below.

Listing 6: Importing a namespace

Imports System

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
Console.Write(salary)
End Sub

Public Shared Sub Main()


Dim employee As Employee
employee = New Employee()
employee.PrintSalary()
End Sub

End Class

Now, you can use the Console class in the PrintSalary method without mentioning the
namespace because the namespace is already imported. Namespaces also allow you to have
classes with the same name in different namespaces. To refer to a class correctly, it is
common practice to mention the namespace in front of the class name. For example, the
Console class in the System namespace is referred to as System.Console.

Access Types
In many cases, when you write a class, you will provide that class to other people so they can
use its functionality, i.e., they can call methods of that class or access its fields. One of the
great benefits of OOP is that you can restrict access to a class member. This means, you have
full control over what you want to expose. You can write methods that can be called by other
programmers, or you can have methods that are not accessible by anyone other than from
inside the class itself.

VB.NET offers levels of accessibility, as follows:

• Public. Public class members don't have access restrictions. You use the keyword
Public in front of the class member to make it available publicly. For example, the
PrintSalary method in the Employee class is a public method. It can be called from
anywhere.
• Private. Private class member can only be accessed from inside the class itself. Use
the Private keyword to make a class member private.
• Protected. A protected member is accessible to a derived class and from inside the
class itself. Use the Protected keyword to make a member protected.
• Friend. Members with the friend access restriction are accessible only within the
program that contains the class declaration. Use the keyword Friend to make a
member have friend restriction.
• Protected friend. This is the union of protected and friend.

These different access types provide for information hiding in OOP. In other words, you can
protect class members that you don't want to expose.

Pages: 1, 2, 3

Next Page

Static Members

Looking at the Employee class in Listings 4, 5 and 6 again, you may wonder why we can use
the Write method of the System.Console class without first instantiating a System.Console
object. This is because in OOP languages there is a special type of member called a static
member. The term shared is also used in VB.NET.

Static means the member is available without having to instantiate an object. For example,
the class called SalaryLevel provides static fields only in Listing 7.

Listing 7: Static members in a class

Class SalaryLevel
Public Shared Level1 As Decimal = 35000
Public Shared Level2 As Decimal = 40000
Public Shared Level3 As Decimal = 45000
Public Shared Level4 As Decimal = 50000
Public Shared Level5 As Decimal = 55000
Public Shared Level6 As Decimal = 60000
Public Shared Level7 As Decimal = 65000
Public Shared Level8 As Decimal = 70000
Public Shared Level9 As Decimal = 75000
Public Shared Level10 As Decimal = 80000
End Class

You can then use the class in your program, as illustrated in Listing 8.

Listing 8: Using a static member of a class

Imports System

Class SalaryLevel
Public Shared Level1 As Decimal = 35000
Public Shared Level2 As Decimal = 40000
Public Shared Level3 As Decimal = 45000
Public Shared Level4 As Decimal = 50000
Public Shared Level5 As Decimal = 55000
Public Shared Level6 As Decimal = 60000
Public Shared Level7 As Decimal = 65000
Public Shared Level8 As Decimal = 70000
Public Shared Level9 As Decimal = 75000
Public Shared Level10 As Decimal = 80000
End Class

Class Employee

Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console, use the static field of SalaryLevel
Console.Write(SalaryLevel.Level4)
End Sub

Public Shared Sub Main()


Dim employee As Employee
employee = New Employee()
employee.PrintSalary()
End Sub

End Class

In the PrintSalary method of the Employee class, we can use the Level4 static field in the
SalaryLevel class without first creating an object of type SalaryLevel. Members that are
not static are called instance members.

Constructors

A constructor is a special method that must be present in a class for the class to get
instantiated. In VB.NET, this method is called New. But, as you have seen, there is no New
method in the classes in the previous code. That's right. When there is no constructor present,
VB.NET will create one for you. When you instantiate an object by using the New keyword,
the class's constructor is called. You can provide initialization code that is guaranteed to run
when the object is instantiated. If you write a constructor explicitly in your class, VB.NET
won't create it anymore.

Inheritance

Inheritance is a feature that allows you to extend a class. If you need some functionality, you
can create a brand new class. If part of the functionality you need has been provided in a class
written by someone else, however, you can then write a new class that extends the original
class. Your class is called the child class or derived class, and the original class is called the
parent class or the base class. The process of extending a class is called extension.
Sometimes, the term subclass or inherit is used to describe the act of extending a class. In
VB.NET a class can only extend one parent class. Multiple class inheritance is not allowed in
VB.NET.

Syntactically, extending a class is done using a semicolon after the class name, followed by
the word Inherits and the parent class name. For example, Listing 9 shows how we extend
the class Employee to create a new class called Manager.

Listing 9: Extending a class

Imports System

Class Employee

Dim salary As Decimal = 40000


Dim yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
Console.Write(salary)
End Sub

End Class

Class Manager: Inherits Employee


End Class

If the word Inherits appears on the next line, you don't need the semicolon.

Class Manager
Inherits Employee
End Class

Now, you can instantiate a Manager object and use members from the Employee class. The
code is given in Listing 10. //////QUESTION: IMPORTS SYSTEM WAS STUCK IN THE
ABOVE GRAF. IT PROBABLY BELONGS AS TEH FIRST LINE OF CODE. CHECK
WITH AU.//////////

Listing 10: Instantiating a Manager object

Imports System

Class Employee

Public salary As Decimal = 40000


Public yearlyBonus As Decimal = 4000

Public Sub PrintSalary()


' print the salary to the Console
Console.Write(salary)
End Sub

End Class

Class Manager: Inherits Employee


End Class

Module Module1
Public Sub Main()
Dim manager As Manager
manager = New Manager()
manager.PrintSalary()
End Sub
End Module

The example in Listing 11 shows how we can extend the Manager class by writing a new
method called PrintBonus.

Listing 11: Adding a method to the derived class

Class Manager: Inherits Employee


Public Sub PrintBonus()
Console.Write(yearlyBonus)
End Sub
End Class

Note that member accessibility restriction applies. For example, you can't make the
yearlyBonus field private, since this field is not accessible from the Manager class.
Therefore, trying to compile the code will result in an error.

Inheritance is a common practice. In fact, the .NET Framework class library consist of
hierarchies of classes that are derived from other classes. For example, the Button class in
the Windows.Forms namespace is a child class of ButtonBase, which itself is a child of
Control. All classes will eventually have the System.Object class as its root.
System.Object is called the root or the superclass in the .NET Framework class library.

The power of inheritance can be demonstrated by the code in Listing 12.

Listing 12: Extending System.Windows.Forms.Form

Public Class MyForm : Inherits System.Windows.Forms.Form


End Class

This blank class declaration, when compiled and run, will display a Windows form. You can
create a form without a single line of code. This is because MyForm inherits
System.WIndows.Forms.Form. It inherits the functionality of the Form class.

NotInheritable Classes

You can prevent classes from being inherited by using the NotInheritable keyword. For
example, the code in Listing 13 is a class called Calculator that cannot be inherited.

Listing 13: A non-inheritable class

NotInheritable Class Calculator


End Class

Trying to extend this class will raise a compile error. Why would you want to make your
class non- inheritable? In some cases, you may not want other people to be able to extend
your class. Another reason is that an inheritable class produces faster code. You should use
inheritable classes with caution, however, because noninheritance defeats the purpose of
OOP. Only use it if you are 100% sure that you will not extend the class. This type of class is
also called a final class in some other OOP languages.

Part 2 of this series can be found here


Object Oriented Programming In VB.NET
Contents

• Introduction
• Using the code
• Lesson 1: Namespaces, Classes & Modules
• Lesson 2: Access Types
• Lesson 3: Shared Functions
• Lesson 4: Overloading
• Lesson 5: Inheritance
• Lesson 6: Overriding
• Lesson 7: Polymorphism
• Lesson 8: Constructors & Destructors
• Lesson 9: Property Routines
• Lesson 10: A Simple Application

Introduction

VB.NET is completely object oriented. This article uncovers some basic Object Oriented
Programming features of Visual Basic. NET. The whole article is divided into ten lessons.
The source code for these lessons is provided with the article.

This tutorial is designed with the following objectives:

1. To provide a sound knowledge about Object Oriented Programming in


VB.NET.
2. To educate how Object Oriented techniques are used in VB.NET.
3. To explain the following concepts in an easy and simple way:
o Creating and using classes and objects in VB.NET.
o Encapsulation, Abstraction, Inheritance and Polymorphism.
o Overloading and Overriding.
o Constructors and Destructors.
o Static functions.

Go through this tutorial and you will start making sense of almost any .NET code. Also,
Java/CPP programmers can use this to understand OOPs in VB.NET.

Using the code

The source code for each lesson is available as a .vb source code file. You need Microsoft
.NET framework SDK installed in your system to compile and execute the exercises in this
article. You can download it from the Microsoft website. The VB.NET compiler (vbc.exe)
normally resides in your FrameworkSDK\bin folder.

To manually compile a source code file, you may use the command prompt to type: vbc
filename.vb /out:"filename.exe" /r:"System.Windows.Forms.dll","System.dll"

Lesson 1: Namespaces, Classes & Objects, Modules

A Namespace
In VB.NET, classes and other data structures for a specific purpose are grouped
together to form a namespace. You can use the classes in a namespace, by simply
importing the namespace. The Imports keyword is used to import a namespace to your
project. .NET framework provides a rich set of built in classes, grouped together to
various namespaces. In this lesson, we are using the System namespace. Import the
System namespace (already available in .NET).

Collapse

Collapse

Imports System

A Class

Probably, you are already familiar with classes and objects. Simply speaking, a Class
is a definition of a real life object. For example, Human is a class for representing all
human beings. Dog is a class to represent all Dogs. Classes can contain functions too.
Animals is a namespace.

Collapse

Collapse

Namespace Animals

Dog is a class in the namespace Animals:

Collapse

Collapse

Class Dog

Bark is a function in this Class:

Collapse

Collapse

Function Bark()
Console.Writeline ("Dog is barking")
End Function
End Class
End Namespace

An Object

An object is an instance of a Class. For example, Jimmy is an object of type Dog. We


will create an object in the next section. Read on.

Modules
You can use modules to write common functions. A Module is a group of functions.
Unlike functions in classes, Public functions in modules can be called directly from
anywhere else. VB provides Functions and Subroutines. Functions and Subroutines are
almost the same, but the difference is that a subroutine can't return a value.

Collapse

Collapse

Public Module modMain

Execution will start from the Main() subroutine:

Collapse

Collapse

Sub Main()
'Call our function. See below

OurFunction()
End sub

OurFunction: Our own little function to use the class Dog:

Collapse

Collapse

Function OurFunction()
'Here is how we declare a variable Jimmy of type Dog.

'We use Animals.Dog because, the class Dog is in the

'namespace Animals (see above).

Dim Jimmy as Animals.Dog

'Create an object. Unlike in VB 6, it is not required to use

'the 'set' keyword.

Jimmy = new Animals.Dog()

'Another way to create an object is

'Dim Jimmy as new Dog

'Call Jimmy's Main Function

Jimmy.Bark()
End Function
End module
Lesson 2: Access Types

The major access types are Public, Private, Friend and Protected. A Class may contain functions,
variables etc., which can be either Public or Private or Protected or Friend. If they are Public, they
can be accessed by creating objects of the Class. Private and Protected members can be accessed
only by the functions inside the Class. Protected members are much like Private members, but
they have some special use while inheriting a Class. We will see this later, in Inheritance
(Lesson 5). Friend members can be accessed only by elements of the same project, and not by
the ones outside the current project. Let us expand our dog class.

Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

Animals is a namespace.

Collapse

Collapse

Namespace Animals

Dog is a class in the namespace Animals.

Collapse

Collapse

Public Class Dog


'A public variable

Public AgeOfDog as Integer

Bark is a function in this class. It is Public:

Collapse

Collapse

Public Function Bark()


Console.Writeline ("Dog is barking")
End Function

Walk is a function in this class. It is Private.

Collapse

Collapse

Private Function Walk()


Console.Writeline ("Dog is walking")
End Function
End Class
End Namespace
Our Module:

Collapse

Collapse

Public Module modMain

Execution will start from the Main() subroutine:

Collapse

Collapse

Sub Main()
'Call our function. See below

OurFunction()
End sub
'OurFunction: Called from Main()

Function OurFunction()
Dim Jimmy as Animals.Dog
Jimmy=new Animals.Dog()
'This will work, because Bark & Ageofdog are public

Jimmy.Bark
Jimmy.AgeOfDog=10
'Calling the Walk function will not work here, because

'Walk() is outside the class Dog

'So this is wrong. Uncomment this and try to compile, it will

'cause an error.

'Jimmy.Walk

End Function
End Module

Additional Notes:

Encapsulation

Putting all the data and related functions in a Class is called Encapsulation.

Data Hiding or Abstraction:

Normally, in a Class, variables used to hold data (like the age of a dog) is declared as
Private. Functions or property routines are used to access these variables. Protecting
the data of an object from outside functions is called Abstraction or Data Hiding. This
prevents accidental modification of data by functions outside the class.

Lesson 3: Shared Functions

The shared members in a class (both functions and variables) can be used without creating
objects of a class as shown. The Shared modifier indicates that the method does not operate on
a specific instance of a type and may be invoked directly from a type rather than through a
particular instance of a type.

Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

Animals is a namespace.

Collapse

Collapse

Namespace Animals

Dog is a class in the namespace Animals.

Collapse

Collapse

Class Dog

Bark is a now a Public, shared function in this class.

Collapse

Collapse

Public Shared Function Bark()


Console.Writeline ("Dog is barking")
End Function

Walk is a Public function in this class. It is not shared.

Collapse

Collapse

Public Function Walk()


Console.Writeline ("Dog is walking")
End Function
End Class
End Namespace

Our Module:

Collapse

Collapse

Public Module modMain

Execution will start from the Main() subroutine.


Collapse

Collapse

Sub Main()
'We can call the Bark() function directly,

'with out creating an object of type Dog -

'because it is shared.

Animals.Dog.Bark()
'We can call the Walk() function only

'after creating an object, because

'it is not shared.

Dim Jimmy as Animals.Dog


Jimmy=new Animals.Dog()
Jimmy.Walk()
'Now Guess? The WriteLine() function we used so far

'is a shared function in class Console :)

'Also, we can write the Main() function itself as a shared

'function in a class. i.e Shared Sub Main(). Try

'moving Main() from this module to the above class

End sub
End Module

Lesson 4: Overloading

Overloading is a simple technique, to enable a single function name to accept parameters of


different type. Let us see a simple Adder class. Import the System namespace (already
available in .NET).

Collapse

Collapse

Imports System
Class Adder

Here, we have two Add() functions. This one adds two integers. Convert.ToString is
equivalent to the good old CStr.

Collapse

Collapse

Overloads Public Sub Add(A as Integer, B as Integer)


Console.Writeline ("Adding Integers: " + Convert.ToString(a + b))
End Sub

This one adds two strings.

Collapse
Collapse

Overloads Public Sub Add(A as String, B as String)


Console.Writeline ("Adding Strings: " + a + b)
End Sub
'And both have the same name. This is possible because, we used the

'Overloads keyword, to overload them.

'Here, we have the Main Function with in this class. When you write.

'your main function inside the class, it should be a shared function.

Shared Sub Main()


Dim AdderObj as Adder
'Create the object

AdderObj=new Adder
'This will invoke first function

AdderObj.Add(10,20)
'This will invoke second function

AdderObj.Add("hello"," how are you")


End Sub
End Class

Lesson 5: Inheritance

Inheritance is the property in which, a derived class acquires the attributes of its base class. In
simple terms, you can create or 'inherit' your own class (derived class), using an existing class
(base class). You can use the Inherits keyword for this.

Let us see a simple example. Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

Our simple base class:

Collapse

Collapse

Class Human
'This is something that all humans do

Public Sub Walk()


Console.Writeline ("Walking")
End Sub
End Class

Now, let us derive a class from Human.

A Programmer is a Human.

Collapse
Collapse

Class Programmer
Inherits Human
'We already have the above Walk() function

'This is something that all programmers do ;)

Public Sub StealCode()


Console.Writeline ("Stealing code")
End Sub
End Class

Just a MainClass.

Collapse

Collapse

Class MainClass
'Our main function

Shared Sub Main()


Dim Tom as Programmer
Tom=new Programmer

'This call is okie because programmer got this function

'from its base class

Tom.Walk()

'This is also correct because Tom is a programmer

Tom.StealCode()
End Sub
End Class

Additional Notes:

• MustInherit

The MustInherit keyword specifies that a class cannot be instantiated and can be used
only as a base class. I.e., if you declare our Human class as "MustInherit Class Human",
then you can't create objects of type Human without inheriting it.

• NotInheritable

The NotInheritable keyword specifies that a class cannot be inherited. I.e., if you specify
'NotInheritable Class Human', no derived classes can be made from the Human class.

Lesson 6: Overriding

By default, a derived class Inherits methods from its base class. If an inherited property or
method needs to behave differently in the derived class it can be overridden; that is, you can
define a new implementation of the method in the derived class. The Overridable keyword is
used to mark a function as overridable. The keyword Overrides is used to mark that a function
is overriding some base class function. Let us see an example.
Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

Our simple base class:

Collapse

Collapse

Class Human
'Speak() is declared Overridable

Overridable Public Sub Speak()


Console.Writeline ("Speaking")
End Sub
End Class

Now, let us derive a class from Human:

An Indian is a Human:

Collapse

Collapse

Class Indian
Inherits Human
'Let us make Indian speak Hindi, the National Language

'in India

'Speak() is overriding Speak() in its base class (Human)

Overrides Public Sub Speak()


Console.Writeline ("Speaking Hindi")
'Important: As you expect, any call to Speak() inside this class

'will invoke the Speak() in this class. If you need to

'call Speak() in base class, you can use MyBase keyword.

'Like this

'Mybase.Speak()

End Sub
End Class

Just a class to put our Main().

Collapse

Collapse

Class MainClass
'Our main function
Shared Sub Main()
'Tom is a generic Human

Dim Tom as Human


Tom=new Human
'Tony is a human and an Indian

Dim Tony as Indian


Tony=new Indian
'This call will invoke the Speak() function

'in class Human

Tom.Speak()
'This call will invoke the Speak() function

'in class Indian

Tony.Speak()
End Sub
End Class

Lesson 7: Polymorphism

Polymorphism is the property in which a single object can take more than one form. For
example, if you have a base class named Human, an object of Human type can be used to hold
an object of any of its derived type. When you call a function in your object, the system will
automatically determine the type of the object to call the appropriate function. For example,
let us assume that you have a function named speak() in your base class. You derived a
child class from your base class and overloaded the function speak(). Then, you create a
child class object and assign it to a base class variable. Now, if you call the speak() function
using the base class variable, the speak() function defined in your child class will work. On
the contrary, if you are assigning an object of the base class to the base class variable, then
the speak() function in the base class will work. This is achieved through runtime type
identification of objects. See the example.

Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

This example is exactly the same as the one we saw in the previous lesson. The only
difference is in the Shared Sub Main() in the class MainClass. So scroll down and see an
example:

Our simple base class:

Collapse

Collapse

Class Human
'Speak() is declared Overridable

Overridable Public Sub Speak()


Console.Writeline ("Speaking")
End Sub
End Class

Now, let us derive a class from Human.

An Indian is a Human.

Collapse

Collapse

Class Indian
Inherits Human
'Let us make Indian speak Hindi, the National Language

'in India

'Speak() is overriding Speak() in its base class (Human)

Overrides Public Sub Speak()


Console.Writeline ("Speaking Hindi")
'Important: As you expect, any call to Speak() inside this class

'will invoke the Speak() in this class. If you need to

'call Speak() in base class, you can use MyBase keyword.

'Like this

'Mybase.Speak()

End Sub
End Class

Carefully examine the code in Main():

Collapse

Collapse

Class MainClass
'Our main function

Shared Sub Main()


'Let us define Tom as a human (base class)

Dim Tom as Human


'Now, I am assiging an Indian (derived class)

Tom=new Indian
'The above assignment is legal, because

'Indian IS_A human.

'Now, let me call Speak as

Tom.Speak()
'Which Speak() will work? The Speak() in Indian, or the

'Speak() in human?

'The question arises because, Tom is declared as a Human,


'but an object of type Indian is assigned to Tom.

'The Answer is, the Speak() in Indian will work. This is because,

'most object oriented languages like Vb.net can automatically

'detect the type of the object assigned to a base class variable.

'This is called Polymorphism

End Sub
End Class

Lesson 8: Constructors & Destructors

Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

A Constructor is a special function which is called automatically when a class is created. In


VB.NET, you should use useNew() to create constructors. Constructors can be overloaded
(see Lesson 4), but unlike the functions, the Overloads keyword is not required. A Destructor is
a special function which is called automatically when a class is destroyed. In VB.NET, you
should use useFinalize() routine to create Destructors. They are similar to
Class_Initialize and Class_Terminate in VB 6.0.

Dog is a class:

Collapse

Collapse

Class Dog
'The age variable

Private Age as integer

The default constructor:

Collapse

Collapse

Public Sub New()


Console.Writeline ("Dog is Created With Age Zero")
Age=0
End Sub

The parameterized constructor:

Collapse

Collapse
Public Sub New(val as Integer)
Console.Writeline ("Dog is Created With Age " +
Convert.ToString(val))
Age=val
End Sub

This is the destructor:

Collapse

Collapse

Overrides Protected Sub Finalize()


Console.Writeline ("Dog is Destroyed")
End Sub
'The Main Function

Shared Sub Main()


Dim Jimmy, Jacky as Dog
'Create the objects

'This will call the default constructor

Jimmy=new Dog
'This will call the parameterized constructor

Jacky=new Dog(10)
End Sub
'The Destruction will be done automatically, when

'the program ends. This is done by the Garbage

'Collector.

End Class

Lesson 9: Property Routines

You can use both properties and fields to store information in an object. While fields are
simply Public variables, properties use property procedures to control how values are set or
returned. You can use the Get/Set keywords for getting/setting properties. See the following
example. Import the System namespace (already available in .NET).

Collapse

Collapse

Imports System

Dog is a class.

Collapse

Collapse

Public Class Dog


'A private variable to hold the value

Private mAgeOfDog as Integer

This is our property routine:


Collapse

Collapse

Public Property Age() As Integer


'Called when someone tries to retreive the value

Get
Console.Writeline ("Getting Property")
Return mAgeOfdog
End Get
Set(ByVal Value As Integer)
'Called when someone tries to assign a value

Console.Writeline ("Setting Property")


mAgeOfDog=Value
End Set
End Property
End Class

Another class:

Collapse

Collapse

Class MainClass
'Our main function. Execution starts here.

Shared Sub Main()


'Let us create an object.

Dim Jimmy as Dog


Jimmy=new Dog
'We can't access mAgeofDog directly, so we should

'use Age() property routine.

'Set it. The Age Set routine will work

Jimmy.Age=30
'Get it back. The Age GEt routine will work

Dim curAge=Jimmy.Age()
End Sub
End Class

Lesson 10: A simple program

Let us analyze a simple program. First, let us import the required namespaces:

Collapse

Collapse

Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing
'We are inheriting a class named SimpleForm, from the

'class System.Windows.Forms.Form
'

'i.e, Windows is a namespace in system, Forms is a

'namespace in Windows, and Form is a class in Forms.

Public Class SimpleForm


Inherits System.Windows.Forms.Form
'Our constructor

Public Sub New()


'This will invoke the constructor of the base

'class

MyBase.New()

Set the text property of this class. We inherited this property from the base class:

Collapse

Collapse

Me.Text = "Hello, How Are You?"


End Sub
End Class
Collapse

Collapse

Public Class MainClass


Shared Sub Main()
'Create an object from our SimpleForm class

Dim sf as SimpleForm
sf=new SimpleForm

'Pass this object to the Run() function to start

System.Windows.Forms.Application.Run(sf)
End Sub
End Class

That is it. Now you can atleast read and understand most of those VB.NET source code, and
probably implement more OOP features in your VB.NET programs. Now, in my next article,
I'll try to cover the patterns and practices in VB.NET.
Polymorphism and Interfaces

Polymorphism is the idea that many classes can provide the same property or method,
without having to worry what type of class it is. For example, both a Dog class and a
Mosquito class would have a Eat method, but they would go about this in very different
ways. However, with Polymorphism, you do not need to worry whether the class is a Dog or
a Mosquito. Instead, you know that both these classes will have methods that are used in
both, such as an Eat method, and a Sleep method. Visual Basic allows you to do this through
Interfaces.

Interfaces provide a template for classes, which forces any classes that use the Interface to
have the same properties and methods as the Interface. For example, an IAnimal interface
(the I standing for Interface) would have Eat, Sleep, Rest and Go methods. Therefore, any
class that uses this Interface, must also have Eat, Sleep, Rest and Go methods. This can be
very useful when programming.

Imagine you have a variable called 'Animal'. When your program starts, the user can select
what animal he/she wants, ie a Dog, Cat, Sheep or Mosquito. Then, the user can control the
animal by pressing buttons telling it to move forward, eat, sleep etc.

Without Polymorphism, you would have to create different variables depending on what
animal was selected, and have different procedures that needed to be called when the user
clicks on a command, depending on the animal.

Using polymorphism, however, you could use different classes, say cDog, cCat etc. All of
these classes would implement an IAnimal interface, which then means that when the user
clicks on a command, your code would simply call the appropriate method (ie Eat), and know
that no matter what type of animal it was, it would have an Eat method. Calling this method,
however, would involve different actions depending on the type of animal... Dog = Bark at
owner, Sheep = Bend over head and eat grass and Mosquito = Find human!

*** Don't forget, that even if you reference a template, the class is still allowed to have its
own properties and methods too! ***

We'll see how to use Polymorphism in the next section.


Object Oriented Programming for VB.NET - Part 2

The new version of Visual Basic, VB7 and also known as VB.NET, offers the full features of
an OOP language. Even though the concept of objects is not entirely new to VB
programmers, writing code in an OOP way probably is. Here is an article for VB
programmers who want to learn OOP and have a quick grasp of it. You also might want to
check out part one of this series.

Method Overloading

A method is either a subroutine or a function. The difference, of course, is that a function in


Visual Basic returns a value, while a subroutine does not. Both functions and subroutines can
accept arguments.

When choosing method names, you should, of course, use a name that reflects what the
method does. But there are situations where you need methods that do similar things but
accept different lists of arguments. For example, you may need a method that prints a double,
as well as a method that prints a string. What do you do? You can write two methods and call
them PrintDouble and PrintString respectively. But you really want to call both methods
Print, because that is what they do.

OOP languages, including VB.NET, allow multiple methods to have the same name, as long
as those methods have different lists of arguments. This is called method overloading. Each
of the methods with the same name is comfortably called an overload. In VB.NET, you add
the keyword Overloads as the first part in the method signature. The use of the Overloads
keyword is optional, however; you can still have methods with the same name without using
the keyword. For example, consider Listing 14, which shows the class Calculator with two
Add methods. The first overload accepts two integers and the second overload accepts two
doubles.

Imports System

Class Calculator

Overloads Public Function Add(a As Integer, b As Integer) As Integer


Add = a + b
End Function

Overloads Public Function Add(a As Double, b As Double) As Double


Add = a + b
End Function

End Class

Module Module1

Public Sub Main()

Dim counter As Calculator


counter = New Calculator()
' pass two integers
Console.WriteLine(counter.Add(1, 5))
' pass two doubles
Console.WriteLine(counter.Add(1.3, 5.9))
End Sub
End Module

In the Main sub in the Module1 module, we instantiate a Calculator object and call the Add
method twice. On the first call to the Add method, we pass two integers, 1 and 5.

' pass two integers


Console.WriteLine(counter.Add(1, 5))

On the second call, we pass two doubles, 1.3 and 5.9.

' pass two doubles


Console.WriteLine(counter.Add(1.3, 5.9))

The smart thing is, the Common Language Runtime knows which method overload to call.
The first call to the Add method returns 6, the second method returns 7.2.

Method overloading can also be found almost everywhere in the .NET Framework Class
Library. Take the Console class in the System namespace as an example. This class has a
method named Write that outputs the representation of a value to the console. The Write
method has 18 overloads. There is one overload that accepts a Boolean, one that accepts an
integer, and so on. These overloads make sure that you can pass any type of data to the Write
method and the method will still work correctly.

Beginners to OOP often make the mistake of thinking that methods can be overloads if the
return values are of different types. This is not the case. In order to be an overload, the
method must accept a unique set of arguments. Two methods with the same name that accept
the same list of arguments will not compile, even though they return different return types.

For instance, the Calculator class in Listing 15 will not compile because the two Add
methods have the same set of arguments, even though the types of their return values are
different.

Listing 15: Incorrect method overloading

Imports System
Class Calculator

Overloads Public Function Add(a As Integer, b As Double) As Decimal


Add = a + b
End Function

Overloads Public Function Add(a As Integer, b As Double) As Double


Add = a + b
End Function

End Class

When you compile the class, it will report the following compile error:

error BC30301: 'Public Overloads Function Add(a As Integer, b As Double) As


Decimal' and 'Public Overloads Function Add(a As Integer, b As Double) As
Double' differ only by return type. They cannot overload each other.
Why doesn't the compiler allow that? Because a function can be called without expecting a
return value. For example, in the case of the erroneous Calculator class, if the compiler
allowed that and the programmer called the Add function by passing an integer and a double
like this:

Dim counter As Calculator


counter = New Calculator()
' pass two integers
counter.Add(1, 5.89)
it would not be clear which overload is being called.

Pages: 1, 2, 3

Next Page

Method Overriding

Sometimes when you extend a base class, you may want to have a method that has the same
name as the one in the base class but does something different. In VB.NET you can do this by
using the keyword Overridable in front of the declaration of the method in the base class.
Then, in the derived class, you use the keyword Overrides in front of the method with the
same name. This technique is called method overriding.

For example, Listing 16 shows a class called Employee with a method called Work. The
method is declared overridable, meaning that the method can be overridden in the inheriting
classes.

Listing 16: An overridable method

Imports System
Class Employee
Overridable Public Sub Work()
Console.Write("I am an employee.")
End Sub
End Class

The code in Listing 17 is a class called Manager that extends the class Employee in Listing
16. In the Manager class, we provide a different implementation for the method Work.

Listing 17: Method overriding

Class Manager: Inherits Employee


Overrides Public Sub Work()
Console.Write("I am a manager.")
End Sub
End Class

You can make a method not overridable by using the keyword NotOverridable. For
example, the Work method in the Employee class in Listing 18 cannot be overridden.
Listing 18: Not overridable method

Imports System
Class Employee
NotOverridable Public Sub Work()
Console.Write("I am an employee.")
End Sub
End Class

Abstract Classes

In some cases, you don't know how to write the implementation of a method in a class at the
time of writing the class. Implementation can only be provided by the inheriting class. Or,
you know that the method will be overridden in the child classes, so why bother providing an
implementation at all? If this is the case, your class is incomplete; this is called an abstract
class. The method that you don't provide implementation for is called an abstract method. An
abstract method is denoted by the MustOverride keyword. The class itself has the
MustInherit modifier because it cannot be instantiated using the New keyword.

For example, the class in Listing 19 is named Shape and it is abstract because one of the
methods (Draw) does not have implementation. Other than that, the class looks like a normal
class.

Listing 19: An abstract class

Imports System
MustInherit Class Shape
Public x As Integer = 9
Public y As Integer = 0

MustOverride Sub Draw()

Public Function GetInfo() As String


GetInfo = "An abstract class"
End Function
End Class

Note that the Draw method does not have the End Sub declaration.

When you extend an abstract class, you must provide implementations for all methods that
must be overridden. Otherwise, the inheriting class itself will be an abstract class and must be
declared with the MustInherit keyword.

The Rectangle and Line classes in Listing 20 inherit Shape.

Listing 20: Inheriting from an abstract class

Class Rectangle: Inherits Shape

Overrides Sub Draw()


' Draw a rectangle here
End Sub

End Class
Class Line: Inherits Shape

Overrides Sub Draw()


' Draw a line here
End Sub

End Class

Interfaces

For beginners, interfaces are probably not very clear. Why would you want to use an
interface at all? An interface defines a contract that classes must adhere to.

An interface is like an abstract class. An abstract class can have methods with or without
implementations; however, an interface can only have methods that don't have
implementation. In an OOP language that supports only single class inheritance like
VB.NET, inheritance plays a very important role. Interfaces enable multiple inheritance in
VB.NET because a VB.NET class can extend multiple interfaces. Extending an interface has
a special term: implement. To implement an interface in VB.NET, you use the keyword
Implements. As with extending an abstract class, you must provide implementations for all
methods in the interface you implement. Otherwise, you must make your class abstract.

An interface is declared using the keyword Interface. Like other types in VB.NET, there is
a naming convention for interfaces. The recommendation is to use the class's naming
convention and prefix the interface name with an I. For example, here are some good names
for interfaces: IScalable, ISerializable, I3DShape, IPolygonShape, etc.

For example, Listing 21 presents an interface called IShape.

Listing 21: An interface called IShape

Interface IShape
End Interface

For a class to implement an interface, the same syntax as class extension is used. In the code
in Listing 22, the class Line implements the IShape interface.

Listing 22: Implementing an interface

Interface IShape
End Interface

Class Line: Implements IShape


End Class

An alternative syntax would be:

Interface IShape
End Interface

Class Line
Implements IShape
End Class
An interface in VB.NET can only have methods, properties and events. An interface cannot
contain a field. All interface members are implicitly public and may not specify an access
modifier. In the class that implements an interface, each method implementation must specify
the interface method that it implements using the keyword Implements, followed by the
name of the interface and the method name. The interface name and the method name are
separated using a period. For example, the code in Listing 23 shows an interface called
IShape with one method called Draw. There is also a class named Line that implements
IShape.

Listing 23: Implementing an interface method

Imports System
Interface IShape
Sub Draw()
End Interface

Class Line
Implements IShape
Sub Draw() Implements IShape.Draw
Console.Write("Draw a line")
End Sub
End Class

You can then instantiate a Line object as you would a normal class. Like abstract classes,
interfaces cannot be instantiated.

Pages: 1, 2, 3 Next Page

Polymorphism

Polymorphism is probably the hardest concept to digest for those new to OOP. Indeed,
polymorphism (literally means "many forms") is probably the most misunderstood term in
OOP because the word has more than one meaning. For example, if you type in the word
polymorphism as a search keyword in an Internet search engine, you will find out that this
word is also used in biology.

In modern software engineering discipline, polymorphism is classified into universal


polymorphism and ad-hoc polymorphism. Universal polymorphism is considered purer than
ad-hoc polymorphism and is also called "true polymorphism." Ad-hoc polymorphism is often
described as "apparent polymorphism." Universal polymorphism is subdivided into
parametric polymorphism and inclusion polymorphism; and ad-hoc polymorphism can be
subdivided into overloading and coercion. These polysyllabic forms of polymorphism are
explained below.

• Parametric polymorphism is the purest form of polymorphism*. The same object or


function can be used uniformly as a parameter in different type contexts without
changes. A function can be thought as parametric polymorphic if it allows the type of
its parameters to be determined by an implicit or explicit type parameter, and then
performs the same kind of work irrespective of the parameter type.
• Inclusion polymorphism is what we know as subtyping and inheritance. This type of
polymorphism allows an object to belong to a number of classes, which are
sometimes overlapping. In other words, a class can be included in another class to
create an inheritance hierarchy.
• Overloading is what is known as method overloading in object-oriented
programming languages. It allows multiple functions to have the same name, yet still
perform different functions.
• Coercion allows a parameter to a function to be converted to the type expected by
that function to avoid a type error.

This classification was put forward by Luca Cardelli (AT&T Bell Laboratories) and Peter
Wegner (Brown University) in their paper, "On Understanding Types, Data Abstraction and
Polymorphism" (PDF), published in Computing Surveys in 1985. This is the presently
accepted definition of polymorphism. The older definition, first put forth by C. Strachey in
1967, identified only two types of polymorphism: parametric polymorphism and ad-hoc
polymorphism.

In OOP, when we talk about polymorphism, it simply means "one interface, many
implementations." To be more specific, the term is used to describe reference variables that
may at run-time refer to objects of different classes. (Overloading is also a type of
polymorphism; however, in OOP it is simply referred to as method overloading.) In other
words, polymorphism (as far as OOP is concerned) simply means that you can assign to an
object reference an object whose type is different from the object reference. In essence, if you
have an object reference a whose type is A, it is legal to assign and object of type B, as in the
following.

Dim a As A
a = New B()

However, B must be derived from A either directly or indirectly, or A must be an interface


that is implemented by B or the class that B extends directly or indirectly.

Consider the example in Listing 24.

Listing 24: An example of polymorphism

Class Employee
Public Overridable Sub Work
System.Console.WriteLine( "I am an employee." )
End Sub
End Class

Class Manager : Inherits Employee


Public Sub Manage
System.Console.WriteLine("Managing ...")
End Sub

Public Overrides Sub Work


System.Console.WriteLine( "I am a manager" )
End Sub
End Class

Module ModMain
Sub Main()
Dim employee As Employee
employee = New Manager
employee.Work
End Sub
End Module
The example has two classes: Employee and Manager. Employee has a method called Sub
and Manager extends the class Employee and adds a new method called Manage. The Main
sub in the module defines an object variable called employee of type Employee.

Dim employee As Employee

However, employee is assigned an object of type Manager, as in

employee = New Manager

Then, when the Work method is called, guess what is written on the console? I am a
manager. This means that it is the Work method of Manager class that gets called.
Polymorphism in action!

But why do we declare employee as Employee in the first place? Why don't we declare
employee as Manager? To ensure flexibility in cases where we don't know whether the object
reference (employee) will be assigned an object of type Manager or something else. The next
example will make it clearer why we use polymorphism.

Say you have a Windows application and you have a method that changes the BackColor
property of a control. You want to be able to pass a Button, a Label or any control that may
be used in a form. For this purpose, you write the subroutine in Listing 25.

Listing 25: The ChangeColor subroutine

Private Sub ChangeColor(_


ByVal control As System.Windows.Forms.Control, _
ByVal color As system.Drawing.Color)

control.BackColor = color
End Sub

You pass two arguments to the ChangeColor sub: a System.Windows.Forms.Control


object and a System.Drawing.Color object. You know that the Control class is the parent
class of all Windows controls. By declaring control as Control, polymorphism allows you
to pass a Control object or any object whose class is derived from the Control class. This
way, you only need one sub for all controls. Without polymorphism, you need a sub for each
type of control. You would have ChangeButtonColor, ChangeLabelColor, etc

The code in Listing 26 iterates all controls in a Windows form and passes each control to the
ChangeColor sub. Running this code will give all controls in the current window a blue
background color.

Listing 26: Passing different controls to the ChangeColor subroutine

Dim control As System.Windows.Forms.Control


For Each control In Me.Controls
ChangeColor(control, Color.Blue)
Next

Summary
By now, you should have a much better understanding of all those cool words I presented at
the beginning of the article. With this understanding, you can start to take advantage of
VB.NET's complete support for object-orienting programming. Happy OOPing!
Introduction to OOP in VB.NET
by Budi Kurniawan
09/23/2002

Visual Basic .NET offers its users, among many other things, a fully object-oriented
programming (OOP) experience. Some former VB6 developers have prepared themselves
well to embrace this new version of the language. Others, however, need more time and
guidance in taking on this new challenge and opportunity. In this VB.NET OOP series, Budi
Kurniawan introduces many facets of object-oriented design and programming to VB
programmers new to OOP. Discussions focus more on OO concepts rather than OO
techniques. In the first article of this series, Budi answers what is probably the most often
asked question by newcomers to OOP: Why OOP? Finally, we look at why VB6
programmers often find it hard to shift to OOP when the OOP itself is not difficult.

Microsoft launched the .NET Framework early this year and overhauled its most popular
language: Visual Basic. With the introduction of the Framework, the language was
reconstructed and given a new name: VB.NET. It's now a language that fully supports object-
oriented programming. It is true that VB6 supported some notion of objects, but lack of
support for inheritance made it unfit to be called an OOP language. For Microsoft, changing
VB is more of a necessity than a choice, if VB is to become one of the .NET Framework
languages and in order for VB programmers to be able to use the .NET Framework Class
Library.

With the change to the language, many VB fans might think that OOP is a natural
progression from procedural programming, and that OO technology is a new technology.
Surprisingly, this is not the case. OO concepts were first introduced in 1966 in a journal paper
titled "SIMULA-An Algol-based Simulation Language." Its authors, Ole-Johan Dhal and
Kristen Nygaard from the University of Oslo and the Norwegian Computing Center (Norsk
Regnesentral), later completed the first OOP language in the world. The language is called
Simula 67, short for simulation language.

You may find it hard to believe that a full-fledged OO language was implemented before
structured programming and when, as OO expert Bertrand Meyer puts it in his book, Object
Oriented Software Construction, "The Vietnam War was still a page 4 item; barricades had
not yet sprung up in the streets of Paris; a mini-skirt could still cause a stir." However, OO
technology did not become popular until the early 1980s, because at the time of invention, it
was considered too radical for practical use. VB only became a fully OOP officially in 2002
and the inventors of this technology, Ole-Johan Dhal and Kristen Nygaard, only got their
Turing Award, considered the Nobel prize of computer science, in 2001 "for ideas
fundamental to the emergence of object-oriented programming, through their design of the
programming languages Simula I and Simula 67."

Why OOP?

OK, enough history. Now, let's discuss why OOP in VB is a good thing. There are many
benefits of OOP that make the technology so popular and the computing science society
grateful to its inventors. Below, I will mention the three most important ones, in no particular
order.

Modularity is Inherent in OOP


Modern software applications tend to become larger and larger. Once upon a time, a "large"
system comprised a few thousand lines of code. Now, even those consisting of one million
lines are not considered that large. When a system gets larger, it starts giving its developers
problems. Bjarne Stroustrup, the father of C++, once said something like this: a small
program can be written in anything, anyhow. If you don't quit easily, you'll make it work, at
the end. But a large program is a different story. If you don't use techniques of "good
programming," new errors will emerge as fast as you fix the old ones.

The reason for this is there is interdependency among different parts of a large program.
When you change something in some part of the program, you may not realize how the
change might affect other parts. Modularity makes maintenance less of a headache.
Modularity is inherent in OOP because a class, which is a template for objects, is a module
by itself. What is the problem for those new to OOP is how to determine what methods and
data should make up a class. This is another topic of its own, though. A good design should
allow a class to contain similar functionality and related data. An important and related term
that is used often in OOP is coupling, which means the degree of interaction between two
classes (modules).

OOP Promotes Reusability

Reusability means that code that has previously been written can be reused by the code writer
and others who need the same functionality provided by the code. It is not surprising, then,
that an OOP language often comes with a set of ready-to-use libraries. In the case of
VB.NET, the language shares the .NET Framework Class Library with other .NET
languages. These classes have been carefully designed and tested. It is also easy to write and
distribute your own library. Support for reusability in a programming platform is very
attractive, because it shortens the time taken to develop an application. In the world where
good programmers are expensive, what else is more appealing?

One of the main challenges to class reusability is creating good documentation for the class
library. How fast can a programmer find a class that provides the functionality he/she is
looking for? Is it faster to find such a class or to write a new one from scratch? In the .NET
Framework Class library, classes and other types are grouped into namespaces. For instance,
the System.Drawing namespace contains the collection of types used for drawing.

VB.NET programmers are lucky, because the .NET Framework comes with good
documentation, with proper indexing and structured and searchable content. Reusability does
not only apply to the coding phase through the reuse of classes and other types; when
designing an application in an OO system, solutions to OO design problems can also be re-
used. These solutions are called design patterns, and to make it easier to refer to each
solution, the pattern is given a name. For example, if you need to make sure that a class can
only have one instance, there is already a solution to it, which is called the "singleton" design
pattern. The early catalog of reusable design pattern can be found in Design Patterns:
Elements of Resusable Object-Oriented Software. In future articles, I will also discuss the use
of these patterns.

OOP Supports Extendibility

Every application is unique. It has its own requirements and specifications. In terms of
reusability, sometimes you cannot find an existing class that provides the exact functionality
that your application requires. However, you will probably find one or two that provide part
of the functionality. Extendibility means that you can still use those classes by extending
them so that they provide what you want. You still save time, because you don't have to write
code from scratch.
In OOP, extendibility is achieved through inheritance. You can extend an existing class, add
some methods or data to it, or change the behavior of methods you don't like. If you know the
basic functionality that will be used in many cases, but you don't want your class to provide
very specific functions, you can provide a generic class that can be extended later to provide
functionality specific to an application.

A good example is the System.Windows.Forms.Form class, which provides basic methods,


properties, and events for a Windows form. To create a form in a Windows application, you
extend this class. Because your application has specific requirements that do not necessarily
exist in other applications' specifications, you can add the methods and data specific to your
need. You save time and programming (and debugging) efforts because you get the basic
functionality of a form for free by extending System.Windows.Forms.Form.

As another example, take a look at the Control class in the System.Windows.Forms


namespace. This class provides basic functionality for a Windows control. For instance, it has
the BackColor property that will be needed by all Windows controls. Other classes that
extend it get this property for free. Examples of classes that extend the Control class are
Label, MonthCalendar, ScrollBar, etc. These classes need the BackColor property as part
of their user interface.

Not every control needs the SetCalendarDimensions method, however; only


MonthCalendar does. Therefore, the designer of the .NET Framework class library didn't put
this method in the Control class, but in the MonthCalendar class. If you create your own
custom control by extending the Control class, your class, too, will get the BackColor
property for free.

VB6 Programmers and OOP

Now, I hope you agree with me that to work within the .NET Framework, VB programmers
need to master OOP. In the light of this, there is bad news and good news. The bad news is,
the VB versions prior to VB .NET, including VBScript and Visual Basic for Applications
(VBA), are not fully OOP languages. It is true that you could use and write COM
components, which are basically objects; this is probably the reason that some people insist
that VB6 is an OOP language. The lack of other OOP features such as inheritance, however,
disqualify previous versions of VB from being an OOP language (for the criteria of an OO
system, see Chapter 2 of Bertrand Meyer's Object-Oriented Software Construction, Second
Edition).

It is probably more appropriate to categorize the old VB into something between a procedural
language and an OOP language. This is bad news for those wanting to learn VB.NET.
Researchers have been arguing about the best way to teach OOP at school; some argue that it
is best to teach procedural programming before OOP is introduced. In many curricula, we see
that the OOP course can be taken when a student is nearing the final year of his/her university
term.

More recent studies, however, have revealed the contrary. Michael Kolling, from the School
of Computer Science and Computer Engineering, Monash University, Australia, explained in
one of his papers why learning OOP seems harder than learning structured programming. He
and other experts argue that it is how OOP is taught, not OOP itself, that makes it such a
difficult task.

Someone with procedural programming skill thinks in a paradigm very different from how
OO programmers view and try to solve problems. When this person needs to learn OOP,
he/she has to go through a paradigm shift. It is said that it takes six to 18 months to switch
your mindset from procedural to object-oriented paradigms. Another study shows that
students who have not learned procedural programming do not find OOP that difficult.

Now the good news. VB.NET is a relatively easy language to program with. VB.NET
programmers do not need to worry about pointers, don't have to spend precious time solving
memory leaks caused by forgetting to destroy unused objects, etc. The .NET Framework also
comes with a very comprehensive class library with relatively very few bugs in its early
version. Once you know the nuts and bolts of OOP, programming with VB.NET is easy.

Conclusion
This article has presented the main benefits of OOP and why procedural
programmers find it hard to learn OOP. OOP is great for writing many types of
applications. A word of caution, though: OOP is not everything. For example,
some people cannot be convinced that using OOP is better at solving
engineering or quantum mechanics problems than procedural programming.
VB.NET OOP Part 2 - Understanding Constructors

Beginners of OOP with VB.NET often don't pay enough attention to constructors. The reason
for this is their classes are usable even without a constructor. What's worse is that many think
constructors are just another type of method, which is simply not true. This article focuses on
constructors, what they are used for, and some examples on using them. Understanding
constructors well helps you write better classes.

For an object to be created from a class, the class needs a constructor. At a glance, a
constructor looks just like a method. However, constructors are used for the sole purpose of
creating an instance of a class. Here are the characteristics of a constructor:

• Always defined as a Sub. It therefore does not have a return value.


• Regardless the name of the class, the constructor in VB.NET is called New.
• Can have any access modifier (Public, Protected, Friend, Private, or default).
• In most cases, a constructor has a Public access modifier.
• A class can have multiple constructors.

Say you write a class called Employee, as given below:

Public Class Employee


Public Sub Work()
System.Console.WriteLine("I am working.")
End Sub
End Class

You can instantiate an object of type Employee by using the New keyword like this:

Dim employee As Employee


employee = New Employee()
employee.Work()

There is nothing in the Employee class definition other than the Work method, yet you still
can construct an Employee object. This seems to contradict the previous statement that you
need a constructor to instantiate an object of a class. What actually happens is the VB
compiler checks for the presence of a constructor in a class it compiles. If none is found, it
automatically adds a no-argument constructor. Therefore, the previous Employee class is
equivalent to the one below:

Public Class Employee


Public Sub New()
End Sub

Public Sub Work()


System.Console.WriteLine("I am working.")
End Sub
End Class

you cannot construct an Employee object using the following code:


Dim employee As Employee
employee = New Employee()

This is because there is now no no-argument constructor in the Employee class. In VB,
constructors must be declared as a Sub and in most cases they have a Public access modifier.
However, a constructor can also have a Protected, Private, Friend, or the default modifier. For
example, you use the Protected or Private modifier in a Singleton class to prevent the user
from directly instantiating an object of that class. Singletons will be discussed in the next
article, "The Singleton Design Pattern."

The Relationship With the Base Class

If a child class extends a base class, the compiler will make a call from the child class'
constructor to the base class' no-argument constructor. The call will be invoked from the first
statement of the child class' constructor. For example, consider the Employee class and the
Manager class that extends Employee, as in the following code:

Public Class Employee


Public Sub New()
System.Console.WriteLine("Employee's constructor.")
End Sub

Public Sub Work()


System.Console.WriteLine("I am working.")
End Sub
End Class

Public Class Manager : Inherits Employee


Public Sub New()
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

When the Manager class' constructor is invoked, like in the following code, the Employee
class' no-argument constructor is also called.

Dim manager As Manager


manager = New Manager()

The result on the console is as follows:

Employee's constructor.
Manager's constructor.

Note that the code in the base class' constructor is run before the code in the child class'
constructor. If the base class does not have a no-argument constructor, the class won't
compile. For example, the following code will produce a compile error because the Employee
class (base class) does not have a no-argument constructor.

Public Class Employee


Public Sub New(ByVal name As String)
System.Console.WriteLine("Employee's constructor.")
End Sub

Public Sub Work()


System.Console.WriteLine("I am working.")
End Sub
End Class

Public Class Manager : Inherits Employee


Public Sub New()
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

This compile error occurs because the compiler adds a call to the base class' no-argument
constructor's on the first line of the child class' constructor. One solution to this problem is to
add a no-argument constructor to the base class. However, if you don't want to do this, you
can use the MyBase keyword to reference any constructor in the base class. Note that since
MyBase is present in the child class' constructor, the compiler does not add another call to the
base class' no-argument constructor. The MyBase statement must be the first line in the
constructor:

Public Class Employee


Public Sub New(ByVal name As String)
System.Console.WriteLine( _
"Employee's constructor with one argument.")
End Sub

Public Sub Work()


System.Console.WriteLine("I am working.")
End Sub
End Class

Public Class Manager : Inherits Employee


Public Sub New(ByVal name As String)
MyBase.New(name)
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

Constructor calls are only valid as the first statement in a constructor. Even if a class does not
explicitly extend another class, you can still call the base class' constructor because every
class implicitly extends the System.Object class if no class is explicitly defined as the base
class. Therefore, the constructor in the Manager class below is valid:

Public Class Manager


Public Sub New(ByVal name As String)
MyBase.New()
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

Thus, MyBase.New() in the Manager class' constructor calls the System.Object class' no-
argument constructor.

Pages: 1, 2 Next Page


Initialization With Constructors

One of the main uses of constructors is for data initialization. When you create an instance of
a class using the New keyword, the compiler does some initialization in the following order:

• Calls the base class' constructor.


• Initializes class-level variables.
• Executes the rest of the class' constructor.

As an example, consider the Manager class below

Public Class Manager : Inherits Employee


Private id As Integer = 88

Public Sub New(ByVal name As String)


MyBase.New(name)
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

First, MyBase.New(name) will be called. Then it will initialize the id private field with the
value 88. Finally, the compiler calls the WriteLine method, as in:

System.Console.WriteLine("Manager's constructor.")

A constructor gives the user of your class a chance to pass a value for the initialization. For
example, consider the following code:

Public Class Manager : Inherits Employee


Private nameField As String
Public Sub New(ByVal name As String)
nameField = name
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

Here the nameField variable is initialized in the constructor. The user of the class can pass a
value for the nameField. For instance, here is the code to pass "John" for the nameField
variable:

Dim manager As Manager


manager = New Manager("John")

And, here is how you pass "Kevin" to the Manager object:

Dim manager As Manager


manager = New Manager("Kevin")
If a class-level variable needs to be initialized in a constructor and the constructor happens to
have an argument with an identical name with the class-level variable, the argument will hide
the class-level variable. To access the class-level variable from inside the constructor, use the
Me keyword. For example, the following Manager class' constructor has an argument with
the same name as a class-level variable, and uses the Me keyword to access the class-level
variable.

Public Class Manager : Inherits Employee


Private name As String
Public Sub New(ByVal name As String)
Me.name = name
System.Console.WriteLine("Manager's constructor.")
End Sub
End Class

Multiple Constructors

A class can have multiple constructors to give the user flexibility in constructing an object.
For example, in the following Manager class there are two constructors. One is a no-
argument constructor and one that accepts a String.

Public Class Manager


Private nameField As String
Public Sub New()
'give nameField a default value
nameField = "Tony"
End Sub

Public Sub New(ByVal name As String)


nameField = name
End Sub
End Class

Here, the user can use either constructor. If the user does not know or does not want to pass a
name value, then he/she can use the no-argument constructor. Otherwise, the second
constructor can be used. Even with constructors that accept different arguments, oftentimes
they execute the same code. Look at the following:

Public Class Manager


Private nameField As String

Public Sub New()


'give nameField a default value
nameField = "Tony"
System.Console.WriteLine("I am the manager.")
End Sub

Public Sub New(ByVal name As String)


nameField = name
System.Console.WriteLine("I am the manager.")
End Sub
End Class
Both constructors execute the following line:

System.Console.WriteLine("I am the manager.")

And in a typical class, there could be multiple lines of code that need to be run in each of the
class constructor. Having the same set of code in two or more different places is not wise,
because if you need something changed, you need to update it in more than one place. A
common technique is to put the code in one constructor and call that constructor from the
other constructors. Now the Manager class' no-argument constructor calls the other
constructor:

Public Class Manager


Private nameField As String

Public Sub New()


'default value for nameField is Tony
Me.New("Tony")
End Sub

Public Sub New(ByVal name As String)


nameField = name
System.Console.WriteLine("I am the manager.")
End Sub

End Class

Using a constructor for initialization also simplifies the code at the client side. For example, a
Manager class has two fields: name and id. You can either let the user access the name and id
fields by making those fields public or by creating a property for each field, or you can create
a constructor that accepts two arguments. Without the constructor, the user code would be:

Dim manager As Manager


manager = New Manager()
manager.id = 77
manager.name = "Tony"

With a constructor, it would be simpler:

Dim manager As Manager


manager = New Manager(77, "Tony")

Forcing an Object to Have a Specific Type

The other use of constructors is to force an object to have a specific characteristic or


behavior. Consider for example the following Person class:

Public Class Person


Private age As Integer
Private male As Boolean 'true indicates a man, false a woman
End Class
Without any explicit constructor, the only constructor the Person class has is a no-argument
constructor. However, all objects constructed using the New keyword will have its male field
False, therefore indicating that the Person is a female. Expectedly, there will be a method or
property that the user can call to set the value of the male field. If the user forgets to call this
method, however, the resulting object can have invalid values.

Using a constructor that accepts a boolean, such as in the following Person class, will solve
the problem.

Public Class Person


Private age As Integer
Private male As Boolean

Public Sub New(ByVal male As Boolean)


Me.male = male
End Sub
End Class

Now the user of your class must supply a boolean for every Person object constructed. There
is no way the user can forget to set this value because the only constructor the Person class
has requires a boolean.

Summary

In this article, you have learned about constructors. In brief, constructors can be used for:

• Initialization.
• Restricting direct instantiation in the Singleton pattern (discussed in a
separate article).
• Determining the type of object that can be created.
What is OOP (Object-oriented programming)?
(5 votes, average: 4.80 out of 5)

Introduction

OOP stands for Object-Oriented Programming. What does it mean? And what’s the
difference between OOP and procedural programming? We’ll go through all these terms,
We’ll demonstrate the difference of these approaches and advantages of the OOP over
procedural concept. Examples are for PHP, but concept is the same in all object-oriented
languages.

So, let’s start with defining, what OOP is and how it differs from procedural programming.
Just take a look around. For example, you see a table. Consider you have to program it. When
using procedural approach, you focus on it’s behaviour (for example, you write function, that
calculates height or that assembles it from the given dimensions). However, table has
properties besides behaviour. When following procedural paradigm, we create variables for
each property – height, width, length, square, weight. All that data – properties (variables)
and behaviour (functions) describe the object from the real world – table. What’s wrong with
this approach? Nothing wrong, everything is fine, when we’re dealing with one table.

Procedural programming – the problem

And now imagine if we have several table types – square, triangle and rounded. Consider the
following task. We have to calculate square of every table. Let’s try to do this with
procedural approach, without any objects. Each table has only one property, that we’re
interested in – side for triangle and square and radius for rounded one. Now we’ll create 3
functions, that calculate the square. (see formulas for equilateral triangle and circle)

1. function calcSquare($side)
2. {
3. return $side*$side;
4. }
5.
6. function calcTriangle($side)
7. {
8. return $side*$side*0.433;
9. }
10.
11.function calcCircle($rad)
12.{
13. return M_PI*$rad*$rad;
14.}

Everything is fine until we have to print list of tables with squares like:

Table Squar
Type
name e

0.95
table 1 circle
m2
triangl 0.78
table 2
e m2

squar
table 3 1 m2
e

To process it, we need one more parameter in our array – the type of the table. And adding it
makes array a 2-dimensional one:

1. $tables = array(
2. array(‘circle’, 0.7),
3. array(‘circle’, 0.8),
4. array(‘square’, 0.9),
5. array(‘triangle’, 1),
6. );

And now let’s program processing of these arrays (using the trick with for loop):

1. echo ‘<table border="1" cellspacing="0" cellpadding="3">’;


2. for ($i = 0, $s = sizeof($tables); $i < $s; $i++)
3. {
4. switch ($tables[$i][0])//we have to define which type we’re dealing
with
5. //and call correct function for it
6. {
7. case ‘circle’:
8. {
9. $square = caclCircle($tables[$i][1]);
10. break;
11. }
12. case ‘square’:
13. {
14. $square = caclSquare($tables[$i][1]);
15. break;
16. }
17. case ‘triangle’:
18. {
19. $square = caclTriangle($tables[$i][1]);
20. break;
21. }
22. }
23. echo ‘
24. <tr>
25. <td>table ‘.($i+1).‘</td>
26. <td>’.$tables[$i][0].‘</td>
27. <td>’.$square.‘ m<sup>2</sup></td>
28. </tr>
29.‘;
30.}
31.echo ‘</table>’;

Yes! We did it – created all the stuff we had to and it works fine. But take a look at this. In
the array we have to specify the table type, then check it and select the corresponding
function. And how about dealing with 10 table types? Adding each type requires adding new
calculation function and changing the printing one.

OOP – solution

And now we’ll take a look at the object-oriented solution. Maybe you’ve heard of the 3
principles of the OO programming – Inheritance, Encapsulation, Polymorphism. And all
of them are used even in this simple example. But before plunging into the OO world, let’s
see, what is object.
When developing, by saying “object” we mean some abstraction of the real world object (not
always real, it may be an abstraction), that has some attributes (called properties or fields)
and behaviour or actions (called methods).
So since object holds both it’s properties and behaviour, we can define 3 classes and use
them all. Yes, we mentioned “classes”. Classes are “blueprints” for objects. Class describes,
what properties the object will have, what methods will work with his properties and how.
And when we need the object of this class to work with, we instantiate it.

Basically, you can imagine class as an empty pot. It has properties:

• contents
• volume

And objects of that class are:

• Big pot with honey (Contents = “honey”, volume=”big”)


• Little pot with water (Contents = “water”, volume=”little”)
• Medium-sized empty pot (Contents = “”, volume=”medium”)

You also can imagine the process of instantiation of the pot as the sequence of operations:

1. Take blueprint (class definition)


2. Create pot from clay (allocate memory according to the class definition)
3. Put something into the pot (Initialize properties with some values)

Steps #1 and #2 are done automatically by the programming language compiler (or
interpreter), and the third step depends on the:

• Class definition – you can specify default values for the properties
• Class constructor – you can define special function, that takes care of
attributes initialization. We’ll talk aabout them later.

So, now we have theory, let’s start coding.

1. class CircleTable
2. {
3. public $radius;//defining property
4.
5. public function getSquare()//and method
6. {
7. return $this->radius*$this->radius*M_PI;
8. }
9. }
10.
11.class SquareTable
12.{
13. public $side;
14.
15. public function getSquare()
16. {
17. return $this->side*$this->side;
18. }
19.}
20.
21.class TriangleTable
22.{
23. public $side;
24.
25. public function getSquare()
26. {
27. return $this->side*$this->side*0.433;
28. }
29.}

In PHP, when we define the property without specifying it’s visibility, it is considered
public. That means, that we can create an object and access it’s public property:

1. $table = new SquareTable();


2. $table->side = 0.7;

Other variants are private and protected. When we define property as private, it can be
accessed only from methods of the same class. This is used for some internal variables.
Protected is the same as private, but it can be accessed from the child classes also. Don’t
worry if you don’t understand the concept now, we’ll go through this later.
Note: In other languages default visibility may be different! (e.g. C++ properties are defined
as private by default)

Refactoring OO solution

Code refactoring is the process of changing a computer program’s internal structure without
modifying its external functional behaviour or existing functionality. This is usually done to
improve external or internal non-functional properties of the software, such as code
readability, simplify code structure, change code to adhere to a given programming paradigm,
improve maintainability, improve extensibility, or increase execution performance.
(Wikipedia)

Now let’s take a close look at these classes. All of them have one parameter and a common
method getSquare(). We can create the parent object – Table and extend these three classes
from it. See the UML diagram:
This should be evident, but we’ll explain what’s there. First of all, we have class Table. It is a
parent class for all tables. Then we have three derived classes (arrow points from child to the
parent class), which override parent’s getSquare() method.
and the code:

1. class Table
2. {
3. public function getSquare()
4. {
5. return 0;
6. }
7. }
8. class CircleTable extends Table
9. {
10. public $radius;
11.
12. public function getSquare()
13. {
14. return $this->radius*$this->radius*M_PI;//note $this variable. It
points to the current object we’re in.
15. }
16.}
17.
18.class SquareTable extends Table
19.{
20. public $side;
21.
22. public function getSquare()
23. {
24. return $this->side*$this->side;
25. }
26.}
27.
28.class TriangleTable extends Table
29.{
30. public $side;
31.
32. public function getSquare()
33. {
34. return $this->side*$this->side*0.433;
35. }
36.}

Make it work!

So, everything is OK now and we can print the same table using defined classes. Unlike
previous approach, we’ll have a simple array of objects here:

1. //creating the objects


2. //in real application it is done much more smart
3. //we’ll see how to do it better a bit later
4. $tables[0] = new CircleTable;
5. $tables[0]->radius = 0.7;
6.
7. $tables[1] = new SquareTable;
8. $tables[1]->side = 0.9;
9.
10.$tables[2] = new TriangleTable;
11.$tables[2]->side = 1;
12.
13.$tables[3] = new CircleTable;
14.$tables[3]->radius = 1;
15.
16.//showing table
17.echo ‘<table border="1" cellspacing="0" cellpadding="2">’;
18.for ($i = 0, $s = sizeof($tables); $i < $s; $i++)
19.{
20. echo ‘
21. <tr>
22. <td>table ‘.($i+1).‘</td>
23. <td>’.$tables[$i]->getSquare().‘ m<sup>2</sup></td>
24. </tr>
25.‘;
26.}
27.echo ‘</table>’;

Note, that we don’t need any function selection, we just call getSquare() for any object. And
since all of them have it (that’s why we defined common parent for them), we get correct
result depending on the object we’re working with.
One more benefit is extending this code. Remember, when using procedural approach, to add
new table type we had to add new function and modify the printing function. Using object-
oriented approach, all we have to do is to create one more class. The printing function (which
may contain complex logic or be hidden from the end-user) remains unchanged. So with
OOP we write less and, at the same time, get much better solutions.

OOP principles explained

This principle, when different actions are performed when calling the same method for
different objects, is called Polymorphism. Inheritance is the simplest thing for
understanding – we used this to inherit (programmers usually say “extend”) three table
classes from the one generic table class.

Finally, encapsulation is about hiding implementation details from the end-used. Let’s take
our example; imagine that there are 2 persons. One of them is excellent mathematician and he
created that 4 classed (base class – Table and 3 derived (child) classes). Other should show
that list. With procedural approach he should take a look at the procedures and write code,
that determines the object type and calls correct function. With OOA (object-oriented
approach) he doesn’t have to know that. He just calls getSquare() and doesn’t care about
anything.

Further improvements

To make these principles more understandable, let’s improve our code and add some data to
the objects. Let’s store height of the table and then print volume, that it occupies.
Volume=Square*Height. Square is calculated differently, formula for volume is the same. So
we add new property to the parent class – $height. And new method – getVolume(). Note,
we don’t change any child class at all!

1. class Table
2. {
3. public $height;
4.
5. public function getSquare()
6. {
7. return 0;
8. }
9.
10. public function getVolume()
11. {
12. return $this->height * $this->getSquare();
13. }
14.}

And here is how it works:

1. $table = new CircleTable;


2. $table->radius = 0.7;
3. $table->height = 0.9;
4. echo ‘Table square = ‘.$table->getSquare().‘
5.
6. Table volume = ‘.$table->getVolume();

Note, that we didn’t define $height or method getVolume() in CircleTable class, this is
inherited from parent class. Don’t you think it’s very convenient?

By the way, we used design pattern here, which is called TemplateMethod – we defined
method getVolume(), which uses method getSquare(). And getSquare() itself is defined in
the derived classes. Read more about this pattern in my future posts

Using constructors

Now let’s do some more improvements – we’ll create constructors for the classes.
Constructor is special function, that is called when object is created. We’ve already
mentioned them. In PHP 5 constructor is defined as a special function, named __construct. It
is a regular method, but it can’t return any value. However, it can be public, private or
protected. Usually, constructors are private unless some design pattern is used (e.g.
Singleton). Here is the code, that uses constructors for smarter object initialization:
1. class Table
2. {
3. public $height;
4.
5. public function __construct($h)
6. {
7. $this->height = $h;//setting the height
8. }
9.
10. public function getSquare()
11. {
12. return 0;
13. }
14.
15. public function getVolume()
16. {
17. return $this->height * $this->getSquare();
18. }
19.}
20.class CircleTable extends Table
21.{
22. public $radius;
23.
24. public function __construct($r, $h)
25. {
26. parent::__construct($h);//calling the constructor of the parent
class, passing height there.
27. $this->radius = $r;//setting the radius
28. }
29.
30. public function getSquare()
31. {
32. return $this->radius*$this->radius*M_PI;
33. }
34.}
35.
36.class SquareTable extends Table
37.{
38. public $side;
39.
40. public function __construct($s, $h)
41. {
42. parent::__construct($h);//calling the constructor of the parent
class, passing height there.
43. $this->side = $s;//setting the side
44. }
45.
46. public function getSquare()
47. {
48. return $this->side*$this->side;
49. }
50.}
51.
52.class TriangleTable extends Table
53.{
54. public $side;
55.
56. public function __construct($s, $h)
57. {
58. parent::__construct($h);//calling the constructor of the parent
class, passing height there.
59. $this->side = $s;//setting the side
60. }
61.
62. public function getSquare()
63. {
64. return $this->side*$this->side*0.433;
65. }
66.}

Here is how to create such classes:

1.
2. $table = new CircleTable(0.7, 0.9);//passing radius and height to the
constructor
3.

The following usage is the same, it just helps to initialize object attributes in one line of code,
encapsulating some preprocessing. For example, we know that height can’t be negative, so
we can correct definition of the Table class:

1. class Table
2. {
3. public $height;
4.
5. public function __construct($h)
6. {
7. if ($h <= 0) $h = 0; //restrict negative values
8. $this->height = $h;//setting the height
9. }
10.
11. public function getSquare()
12. {
13. return 0;
14. }
15.
16. public function getVolume()
17. {
18. return $this->height * $this->getSquare();
19. }
20.}

So you can see, using constructors is VERY handy.


Note, if you have the properties public (like in this example), you may still use $table-
>radius to access it.

Attributes and methods access

Finally, let’s take a look at the properties and methods visibility. As we already mentioned,
there are three access levels:

1. Public – accessible both from class itself ($this->property) and from


outside ($user->login)
2. Protected – accessible from the class itself and from it’s derived classes
($this->property, property may be defined in current class or in the parent
one)
3. Private – accessible only from the class itself ($this->property, property
should be defined in the current class)

To demonstrate this in action, we’ll modify the Table class and make it’s $height property
private. Since it is used only in getVolume() method, which is also defined in the Table class,
it should work fine. Also, we add a new method setHeight(). This will be used to modify
height since we’ll not have access to it through $table->height. So here is UML and the code:

1. class Table
2. {
3. private $height;
4.
5. public function __construct($h)
6. {
7. $this->setHeight($h);
8. }
9.
10. public function setHeight($h)
11. {
12. if ($h <= 0) $h = 0; //restrict negative values
13. $this->height = $h;//setting the height
14. }
15.
16. public function getSquare()
17. {
18. return 0;
19. }
20.
21. public function getVolume()
22. {
23. return $this->height * $this->getSquare();
24. }
25.}

Note, that we changed constructor, not it doesn’t set the height itself, it delegates this to the
special setter function, which perform all validation. This is a good practice – to have
attributes of an object hidden and have getter/setter methods to access it. Why? Because this
way you control, what is returned and what is set and can ensure that object’s properties are
always correct.
When using this definition, we’ll not be able to access $height in CircleTable or
TriangleTable. To enable this, we can either add getter method or make $height protected.
First variant will allow everybody to get the height. Second variant allows to get the $height
only within the derived classes (see protected access level above)
Glossary

• Class is a formal definition of some real object or it’s abstraction. It


contains definition of it’s both properties and methods.
• Object is an instantiated class
• Property is a special variable, that represents some attribute of an
object. Sometimes it is called “member variable”
• Method is a special function, that describes some behaviour of an object.
• Constructor is a special method, that is called when object is created.
This is mainly used for the object initialization.
• Getter is a special method, that returns property value. Usually used for
private or protected properties or for some kind of processing before
returning.
• Setter is a special method, that sets property value. Used for private or
protected variables or for some additional validation.
• Superclass is same as parent class or base class
• Subclass is same as derived class, child class, extended class
• Inheritance is an OOP principle, which is used to define some common
behaviour in the base class and then extend it and use in the derived
classes.
• Encapsulation is an OOP principle, which used for hiding implementation
details from the end-user. (remember example with two programmers
developing these table classes)
• Polymorphysm in an OOP principle, which allows different classes to
behave differently when calling the same method.
• Design pattern is some standard proven solution to the common
problem. For example, Singleton pattern solves the problem when we
need some common resource in different places of an application. For
example DB abstraction object.
• Refactoring is the process of changing the source code to make it work
faster, look better, use better solutions, be better in support and future
development

You might also like