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 realworld 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.

println("cadence:"+cadence+" speed:"+speed+" gear:"+gear). } } The syntax of the Java programming language will look new to you. That's because it's not a complete application.out. The following Bicycle class is one possible implementation of a bicycle: class Bicycle { int cadence = 0. it's just the blueprint for bicycles that might be used in an application. } void speedUp(int increment) { speed = speed + increment. Bicycle bike2 = new Bicycle(). } void changeGear(int newValue) { gear = newValue. and gear represent the object's state. and the methods (changeCadence. we say that your bicycle is an instance of the class of objects known as bicycles. changeGear. Each bicycle was built from the same set of blueprints and therefore contains the same components. } void printStates() { System. but the design of this class is based on the previous discussion of bicycle objects. A class is the blueprint from which individual objects are created. speedUp etc. You may have noticed that the Bicycle class does not contain a main method. The fields cadence. void changeCadence(int newValue) { cadence = newValue. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. } void applyBrakes(int decrement) { speed = speed . In objectoriented terms. speed. int gear = 1. 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(). // Invoke methods on those objects . all of the same make and model.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.decrement. int speed = 0.) define its interaction with the outside world.

giving them a lower gear ratio. bike1. bike2. bike2. . Bicycle now becomes the superclass of MountainBike. bike2.changeCadence(40). bike2. for example. bike1. road bikes have drop handlebars. bike2.changeGear(3). some mountain bikes have an additional chain ring.bike1.changeCadence(50). current pedal cadence. speed.printStates(). and tandem bikes. current gear).speedUp(10). bike2. bike1. 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.printStates().changeGear(2). road bikes. all share the characteristics of bicycles (current speed.changeGear(2). Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In the Java programming language. In this example. Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars. Mountain bikes. RoadBike. bike2.speedUp(10). } } The output of this test prints the ending pedal cadence. and TandemBike.changeCadence(50).speedUp(10). and each superclass has the potential for an unlimited number of subclasses: A hierarchy of bicycle classes. each class is allowed to have one direct superclass.

might appear as follows: interface Bicycle { void changeCadence(int newValue). are the interface between you and the electrical wiring on the other side of its plastic casing. you must take care to properly document the state and behavior that each superclass defines. an interface is a group of related methods with empty bodies. } // wheel revolutions per minute To implement this interface. In its most common form. use the extends keyword. What Is a Package? . for example. However. This makes code for your subclasses easy to read. void applyBrakes(int decrement). void speedUp(int increment). What Is an Interface? As you've already learned. and this contract is enforced at build time by the compiler. the name of your class would change (to a particular brand of bicycle. void changeGear(int newValue). A bicycle's behavior. such as ACMEBicycle). for example. the buttons on the front of your television set. Note: To actually compile the ACMEBicycle class. Methods form the object's interface with the outside world. 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. You'll learn the reasons for this later in the lessons on Classes and Objects and Interfaces and Inheritance. At the beginning of your class declaration. objects define their interaction with the outside world through the methods that they expose. If your class claims to implement an interface. Interfaces form a contract between the class and the outside world. if specified as an interface. since that code will not appear in the source file of each subclass. you'll need to add the public keyword to the beginning of the implemented interface methods. all methods defined by that interface must appear in its source code before the class will successfully compile. 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.The syntax for creating a subclass is simple. You press the "power" button to turn the television on and off. yet allows its code to focus exclusively on the features that make it unique.

fields. the programmer. Questions and Exercises: Object-Oriented Programming Concepts Questions 1. to focus on the design of your particular application. There are literally thousands of classes to choose from. and methods supplied by the Java Platform 6. create an interface that defines its behavior. 5. Real-world objects contain ___ and ___. images in another. various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. A blueprint for a software object is called a ___. 3. 4. a Socket object allows for the creation and use of network sockets. The term API stands for ___? Exercises 1. 8. Its packages represent the tasks most commonly associated with generalpurpose programming. compare. Standard Edition. The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. As a programmer. Conceptually you can think of packages as being similar to different folders on your computer. A software object's state is stored in ___. A software object's behavior is exposed through ___. The Java Platform API Specification contains the complete listing for all packages. 6. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes. inspect. then require your class to implement it. Load the page in your browser and bookmark it. Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword. This allows you. . A collection of methods with no implementation is called an ___. A namespace that organizes classes and interfaces by functionality is called a ___. You might keep HTML pages in one folder. and scripts or applications in yet another. and accessing it only through publicly exposed methods is known as data ___. This library is known as the "Application Programming Interface". Omit one or two methods and try compiling. 9. delete. or modify a file on the filesystem. 2. a String object contains state and behavior for character strings. a File object allows a programmer to easily create. Create new classes for each real-world object that you observed at the beginning of this trail.A package is a namespace that organizes a set of related classes and interfaces. Hiding internal data from the outside world. For each new class that you've created above. classes. For example. What does the error look like? Check your answers. rather than the infrastructure required to make it work. Refer to the Bicycle class if you forget the required syntax. it makes sense to keep things organized by placing related classes and interfaces into packages. or "API" for short. 2. 7. it will become your single most important piece of reference documentation. interfaces.

keeping it short and to the point. Hard to explain in short. Everything has to be contained within a class. I'll provide a final solution. this is also a drawback of OOP. and Procedural. this is much less common than object oriented programming nowadays. procedural programming is also known as "Functional Programming. to demonstrate the various styles. What about if you just want one function to do something really simple? (Obviously. which is the simplest possible. This is why I'll be offering a demonstration. This is the most common style of programming in the industry. procedural programming is entirely a 1-way system. the main reason that I like C++ is that it allows the programmer to combine procedural programming with OOP. and "fizz buzz" if it is divisible by both 3 <strong class="bbc">and</strong> 5. these styles have their benefits and their liabilities. But solutions often combine all these styles. Aspect Oriented Programming: Often written to complement an OOP solution. The whole purpose is to create code that is well managed. put simply? Object Oriented Programming: A style of programming which is based around objects. printing "fizz" if the number is a multiple of 3. I keep it on more of a "layman's terms" basis. solutions often combine these styles. Of course. (Everything but objects. Take a look at Java. in order to create the most managed code. Procedural Programming: This is the "old school" style of programming. using the widely known "fizz buzz" example: Print numbers 1 to 100. as an example. There's no major data grouping (the main benefit of OOP) so you're basically working with nothing more than variables. and functions. I need to break it down into more functions than necessary. At the end of this entry. it's main use is to keep your OOP code organised." Basically. How do I know which is best for me? Like I already said.<br> <strong class="bbc">NOTE:</strong> The solution offered <em class="bbc">will</em> be a little impractical.This article is going to cover three methods of programming: Object Oriented. this doesn't mean that procedural programming is without benefits! In fact. "buzz" if it is a multiple of 5. so you'll be reading this again in a bit) . basically) The obvious benefit to procedural programming is that you don't need objects for everything. These sound interesting. So what are they. Time to get into the more nitty-gritty stuff~ Procedural Programming Like I said.<br> <br> To those of you who know me: You know that I'm not much of a writer. but basically. Less commonly used now~ The main language (which is still used within the industry) which still focuses on this style is C. Aspect Oriented. loops. without having to scatter various aspects of code across several objects. However.

// our function to perform the fizz buzz operation 06 bool ByThree(int). 10 11 int main() { 12 13 14 } 15 16 void FizzBuzz() { 17 18 19 20 21 22 23 24 25 26 } 27 28 bool ByThree(int x) {return (x % 3 == 0 ? true : false).The main drawback is that there is no major data grouping.} 31 void PrintBuzz() {printf("buzz").} 30 void PrintFizz() {printf("fizz"). return 0. i). so this could be solved by a global variable. it's easy to keep everything organised~ Variables and methods go in the appropriate classes. } int i = 1.. It's been broken down into various functions to create a better demonstration. // a function to print the word "Fizz" // a function to print the word "Buzz" . Here's the previously mentioned example. but no one likes global variables.} 29 bool ByFive(int x) {return (x % 5 == 0 ? true : false).} printf("\n"). for (i. i++) { if (ByThree(i)) PrintFizz(). 09 void PrintBuzz(). // a function to check if a number is divisible by 5 08 void PrintFizz(). this is not the best way to tackle this problem. if (!ByThree(i) && !ByFive(i)) printf("%d"..h> 02 03 // no objects here! 04 05 void FizzBuzz(). // a function to check if a number is divisible by 3 07 bool ByFive(int). i <= 100. 01 #include <stdio. Remember. FizzBuzz(). With an object oriented language. The key point to notice here is that our variable has to be passed around to various functions. OK. if (ByFive(i)) PrintBuzz().

01 #include <cstdio> 02 03 class FizzBuzz { 04 public: // our publicly accessable stuff void Execute(). The key thing to notice now is that we no longer need to pass that variable around everywhere. if (this->ByFive()) this->PrintBuzz().wikipedia. for (i.. containing these general methods. 5 void PrintFizz(). and call the methods from this class each time. it's a way to store variables.For more information: http://en.ral_programming Object Oriented Programming OOP is a great way to manage your data. It simply gets accessed from within the object. i <= 100. 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. Remember the key benefit of procedural programming? Well it's time for a reminder. // the variable which we will use in our loop bool ByThree(). Another way is to create a base class. Also. 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. Put simply. 13 14 void FizzBuzz::Execute() { 15 16 17 18 19 this->i = 1. that only the class really needs int i. you'll have to take into account how this object is going to need to interact with various other objects. since it takes more planning. // a function to check if a number is divisible by . to create an object. What if you have a method to do something. Then.. Time for that example again. void PrintBuzz(). each of your objects which require the method will inherit it from the base class. One way would be to use a "general" class. When creating your objects. // our function to perform the fizz buzz 05 operation 06 07 08 09 10 11 12 }. This could be considered a disadvantage. i++) { if (this->ByThree()) this->PrintFizz(). and methods together. there are solutions to this. // a function to print the word "Fizz" // a function to print the word "Buzz" // a function to check if a number is divisible by public: // our private stuff. it can sometimes be awkward to come up with the best way for your object to interact with another.. if (!this->ByThree() && !this->ByFive()) 3 bool ByFive().

(That's potato chips. Consider AOP to be a way to meet requirements which are later added to a specification. right? Do you think they start from scratch when they make these changes? More likely.wikipedia.wikipedia. asking you to alter the application to meet some new requirements. and a few years later.. AOP is used to separate your solution into various aspects. AOP is used to allow an application to grow as time progresses. instead of completely re-inventing the flavour. It allows a programmer to modify a static object-oriented solution to create a system which is capable of growing and meeting new requirements. if you're in America ) The manufacturers are always reducing the salt content. we're finally done! Thanks for reading! .. For more information: http://en. You will develop an object-oriented solution for a client.} 29 void FizzBuzz::PrintBuzz() {printf("buzz"). Rather than going through all the old code. your client comes back to you. they would make alterations. It best complements OOP concepts. return 0. Consider a packet of crisps.ted_programming And after all that. as previously stated.} 30 31 int main() { 32 33 34 35 } FizzBuzz *fb.ted_programming Aspect Oriented Programming Basically...} 27 bool FizzBuzz::ByFive() {return (this->i % 5 == 0 ? true : false). The best way to explain AOP is to compare it to an object in the real world. } 26 bool FizzBuzz::ByThree() {return (this->i % 3 == 0 ? true : false). you will dynamically change the application. fb->Execute().} 28 void FizzBuzz::PrintFizz() {printf("fizz"). and making them taste better. printf("\n").. i). The best way to explain is with an example of something other than code. No demonstrations here.20 21 22 23 24 } 25 printf("%d". For more information: http://en..

" is really. Functional programming is Declarative. ABCL: ABCL/1.Procedural. Declarative programming tells the computer what to do. but this: "Like I said. Just replace "variable" with "attribute". Procedural and Object Oriented programming are Imperative. the main reason that I like C++ is that it allows the programmer to combine procedural programming with OOP. ABCL/c+ o Agora o Cecil o Cel . only that. It could seriously mislead people on this site. "procedure or function" with "method". Imperative programming tells the computer how to do something. this doesn't mean that procedural programming is without benefits! In fact. functional. A pure functional language has no side effects. They are different. And a program is a chain of functions where the results of one are the parameters of another. and imperative programming styles are very similar. There is imperative programming and declarative programming. This means that each function takes parameters and gives back results. I'm a bit surprised you haven't corrected this by now. I'm not sure you quite understand what functional programming is (or at least you didn't at this time). ABCL/R2. procedural programming is also known as "Functional Programming. but not how to do it in details. It involves algorithms. Not really. this is much less common than object oriented programming nowadays. a step by step description of what is to be done. Just look at the code and you will see they are almost the same. etc. A side effect would be something like storing a value in some place in memory or printing something on the screen. This is really old. really wrong. Procedural and OO are very similar. ABCL/R. Languages with object-oriented features [oop languages] • • • • • • • • • • • • • • • ABAP Ada 95 AmigaE BETA Blue Boo C++ C# COBOL Cobra ColdFusion Common Lisp COOL CorbaScript Clarion • • • • • • • Omnis Studio Oz o Mozart Programming System Perl since v5 PHP5 Pliant PRM Prototype-based languages o Actor-Based Concurrent Language. However.

NET (VB.NET) o VBScript o Visual Basic for Applications (VBA) Visual FoxPro Visual Prolog Tcl o Xotcl similar to CLOS o Snit uses delegation o incr Tcl (itcl) similar to C++ XBase++ extends xBase standard language o ZZT-oop .• • • • • • • • • • • • • • • • • • CLU Curl D Dylan E Eiffel o Sather Falcon FreeBASIC F-Script F# Fortran 2003 FPr Gambas Graphtalk IDLscript J JADE Java o Groovy o Join Java o X10 Lasso Lava Lexico Lingo LISP Logtalk MATLAB Modula-2 o Modula-3 Nemerle Noop NetRexx Oberon (Oberon-1) o Oberon-2 Object Pascal o Delphi o Free Pascal o Turbo Pascal Object REXX Objective-C • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • Objective Caml • ECMAScript  ActionScript  JavaScript  JScript o Etoys in Squeak o Io o Lua o Lisaac o MOO o NewtonScript o Obliq o REBOL o Self Python REALbasic Revolution Ruby Scala SenseTalk Simula Smalltalk o Self o Bistro o Squeak S o R Squirrel Superx++ TADS Ubercode Visual Basic o Visual Basic .

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 .

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 . a class implementing abstract class Stack-based memory allocation Shallow copy.• • • • Reflection Responsibility-driven design Reverse polymorphism Run-time type information [edit] S • • • • • • • • • • • • • • • • • • Scope Shadowed name Single-assignment variable Singly rooted hierarchy Slicing Specification class. 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. as opposed to Deep copy Single Responsibility Principle Static method Statically typed language.

The 'object interface'. [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.3 Designing concepts o 2. such as concurrency or data storage. An objectoriented program is described by the interaction of these objects. it captures concepts in the problem domain.1 Input (sources) for 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. which does not include object prototype-based approaches where objects are not typically obtained by instancing classes but by cloning other (prototype) objects.4 Output (deliverables) of object-oriented design o 2. and in practice the results of one activity can feed the other in a short feedback cycle through an iterative process. Realize that an output artifact does not need to be completely developed to serve as input of object-oriented design. . Contents [hide] • • • • • 1 Overview 2 Object-oriented design topics o 2. how the object can be interacted with. It is one approach to software design. is also defined. 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.2 Object-oriented concepts o 2. 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. Both analysis and design can be performed incrementally. What follows is a description of the class-based subset of object-oriented design.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. analysis and design may occur in parallel. The conceptual model is explicitly chosen to be independent of implementation details.

not only that object. the events that external actors generate. Relational data model (if applicable): A data model is an abstract model that describes how data is represented and used. Each object serves a separate function. their order. 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. 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. creating class diagram from conceptual diagram: Usually map entity to class. User interface documentations (if applicable): Document that shows and describes the look and feel of the end product's user interface. but it helps to visualize the end-product and therefore helps the designer. taken together. 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. since the strategy chosen for object-relational mapping is an output of the OO design process. lead to a system doing something useful. It is defined by its properties. However. It is not mandatory to have this. . Polymorphism: The ability to replace an object with its subobjects. or object (an object is created based on a class). Use case actors may be end users or other systems. • • • [edit] Object-oriented concepts The five basic concepts of object-oriented design are the implementation level features that are built into the programming language. In many circumstances use cases are further elaborated into use case diagrams. An object can be part of a class. and the growth of an artifact can stimulate the refinement of other artifacts. Interface: The ability to defer the implementation of a method. for a particular scenario of a use case. • • • • [edit] Designing concepts • Defining objects. Use case diagrams are used to identify the actor (users or other systems) and the processes they perform. it is possible to develop the relational data model and the object-oriented design artifacts in parallel. The ability to define the functions or methods signatures without implementing them. Inheritance: The ability for a class to extend or override functionality of another class. what it is and what it can do. the relational data model should usually be created before the design. System Sequence Diagram: System Sequence diagram (SSD) is a picture that shows.• Use case: Use case is a description of sequences of events that. This is called a class. Information hiding: The ability to protect some components of the object from external entities. If an object database is not used. and possible inter-system events. This is realized by language keywords to enable a variable to be declared as private or protected to the owning class. which is a set of objects that are similar. The ability of an object-variable to contain. but also all of its subobjects.

for example. 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. Use design patterns (if applicable): A design pattern is not a finished design. Acyclic dependencies principle: The dependency graph of packages or components should have no cycles. as horizontal arrows. without specifying the final application classes or objects that are involved. being passed a database connection as an argument to the constructor instead of creating one internally. much time is saved for the developer. package C depends on package B. their attributes.• • Identifying attributes. in a context[1]. since he/she is saved the task of rewriting large amounts of standard code for each new application that is developed. Object-oriented design patterns typically show relationships and interactions between classes or objects. and the relationships between the classes. If package A also depended on package C. as parallel vertical lines. then you would have a cycle. If a relational database is used. A sequence diagram shows. Composite reuse principle: Favor polymorphic composition of objects over inheritance . it is a description of a solution to a common problem. The main advantage of using a design pattern is that it can be reused in multiple applications. the messages exchanged between them. 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. and. Identify and define remote objects (if applicable). [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. [2] For example. • 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. in the order in which they occur. which depends on package A. 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. • • • [edit] Output (deliverables) of object-oriented design • Sequence Diagrams: Extend the System Sequence Diagram to add specific objects that handle the system events. different processes or objects that live simultaneously. This is also referred to as having a directed acyclic graph. design the object relation mapping. Identify persistent objects/data (if applicable): Identify objects that have to last longer than a single runtime of the application. By bundling a large amount of reusable code into a framework.

.

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: .

1 Decoupling 4 Formal semantics 5 OOP languages o 5. As programs grow in size. Many modern programming languages now support OOP.2 Gang of Four design patterns o 6. With designs of this sort.6 Responsibility vs. messaging. it is common for the program's data to be accessible from any part of the program. Contents [hide] • • • • • • • • • • • 1 Overview 2 History 3 Fundamental concepts and features o 3. Programming techniques may include features such as data abstraction.5 OOP and control flow o 6.• 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. More complex programs will group lists of commands into functions or subroutines each of which might perform a particular task. 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. allowing any function to modify any piece of data means that bugs can have wide-reaching effects. and inheritance. modularity. nonOOP programs may be one long list of commands.1 Inheritance and behavioral subtyping o 6.3 Object-orientation and databases o 6.1 OOP in dynamic languages 6 Design patterns o 6. .4 Matching real world o 6. polymorphism. Simple. encapsulation.

while concealing the specifics of how those tasks are accomplished. This more conventional approach. The programming construct that combines data with a set of methods for accessing and managing those data is called an object.By contrast. Object-oriented programming has roots that can be traced to the 1960s. reflecting the different kinds of data each contains. For instance. A program might well contain multiple copies of each type of object. This approach can also be used to offer standardized methods across different types of objects. enabling collaboration through the use of linked modules (subroutines). As an example. each instance of which ("objects") contains all the information needed to manipulate its own data structure ("members"). Each object can be viewed as an independent "machine" with a distinct role or responsibility. processing data. a hockey player. manageability often became a concern. each object is capable of receiving messages. but all the different print methods might be called in the same standardized manner from elsewhere in the program. in which a program is seen as a list of tasks (subroutines) to perform. and sending messages to other objects. and to assist in that use. tends to consider data and behavior separately. Each type of object might implement that print method in a different way. An object can also offer simple-to-use. An object-oriented program will usually contain different types of objects. The technology focuses on data rather than processes. This is in contrast to the existing modular programming that had been dominant for many years that focused on the function of a module. The object's methods will typically include checks and safeguards that are specific to the types of data the object contains. . but the data inside each object would differ reflecting the different history of each account. several different types of objects might offer print methods. As hardware and software became increasingly complex. the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. Objects can be thought of as wrapping their data within a set of functions designed to ensure that the data are used appropriately. rather than specifically the data. standardized methods for performing particular operations on its data. Each copy of the bank account object would be alike in the methods it offers for manipulating or reading its data. An object-oriented program may thus be viewed as a collection of interacting objects. 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. but equally provided for code reuse. reusable units of programming logic[citation needed]. as opposed to the conventional model. In OOP. OOP data structures tend to 'carry their own operators around with them' (or at least "inherit" them from a similar object or class). commonly called methods. one for each of the real-world objects the program is dealing with. 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. and self-sufficient reusable units of programming logic. which still persists. with programs composed of self-sufficient modules ("classes"). Instead the data is accessed by calling specially written 'functions'. or a bulldozer. The actions (or "methods") on these objects are closely associated with the object. which are either bundled in with the data or inherited from "class objects" and act as the intermediaries for retrieving or modifying those data. Researchers studied ways to maintain software quality and developed object-oriented programming in part to address common problems by strongly emphasizing discrete. For example. 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. there could be one bank account object for each realworld account at a particular bank.

[3] Another early MIT example was Sketchpad created by Ivan Sutherland in 1960-61. The language also used automatic garbage collection that had been invented earlier for the functional programming language Lisp.[5][8] Simula introduced the notion of classes and instances or objects (as well as subclasses. albeit specialized to graphical interaction. Its dominance was further enhanced by the rising popularity of graphical user interfaces.[4] Also.[5][6] Objects as a formal concept in programming were introduced in the 1960s in Simula 67. written in Objective-C. eventually led to the Common Lisp Object System (CLOS. Some[who?] feel that association with GUIs (real or perceived) was what propelled OOP into the programming mainstream. Object Pascal. 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.[10][11][12] C++[citation needed]. Kay's Smalltalk work had influenced the Lisp community to incorporate objectbased techniques that were introduced to developers via the Lisp machine. coroutines. AED-0. dynamic messaging extension to C based on Smalltalk. The ideas of Simula 67 influenced many later languages. virtual methods. Simula was used for physical modeling. Sutherland defined notions of "object" and "instance" (with the class concept covered by "master" or "definition"). derivatives of LISP (CLOS). In the 1970s. . an object-oriented. OOP toolkits also enhanced the popularity of event-driven programming (although this concept is not limited to OOP). and discrete event simulation) as part of an explicit programming paradigm. and Delphi[citation needed].[1][2] Alan Kay was later to cite a detailed understanding of LISP internals as a strong influence on his thinking in 1966. which was developed at Xerox PARC (by Alan Kay and others) in the 1970s. These included Visual FoxPro 3. there were a few attempts to design processor architectures that included hardware support for objects in memory but these were not successful. linked data structures ("plexes". in that dialect) directly with procedures. a major revision of Simula I. Examples include the Intel iAPX 432 and the Linn Smart Rekursiv.0. introduced the term object-oriented programming to represent the pervasive use of objects and messages as the basis for computation.[9] Smalltalk and with it OOP were introduced to a wider audience by the August 1981 issue of Byte Magazine. "methods" and "member functions". created by Ole-Johan Dahl and Kristen Nygaard of the Norwegian Computing Center in Oslo. such as models to study and improve the movement of ships and their content through cargo ports. ANSI Common Lisp). prefiguring what were later termed "messages". which integrates functional programming and object-oriented programming and allows extension via a Metaobject protocol. Smalltalk creators were influenced by the ideas introduced in Simula 67. "object" could refer to identified items (LISP atoms) with properties (attributes). and C++. an MIT ALGOL version. An example of a closely related dynamic GUI library and OOP language can be found in the Cocoa frameworks on Mac OS X. In the 1980s. a programming language designed for discrete event simulation. a part of the first standardized object-oriented programming language. as early as 1960. in the glossary of the 1963 technical report based on his dissertation about Sketchpad. which rely heavily upon object-oriented programming techniques. including Smalltalk.[7] Simula 67 was influenced by SIMSCRIPT and Hoare's proposed "record classes". In the environment of the artificial intelligence group. Object-oriented programming developed as the dominant programming methodology in the early and mid 1990s when programming languages supporting the techniques became widely available. The Smalltalk language.[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. Experimentation with various extensions to Lisp (like LOOPS and Flavors introducing multiple inheritance and mixins).

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 objectorientation, sometimes called object-based languages. Examples: Modula2 (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.

Object-relational mapping. in particular in all those that allow mutable objects. Proxy Pattern Behavioral patterns (11): Chain of Responsibility Pattern. there is a general need to bridge the two worlds. Decorator Pattern. Memento Pattern. Singleton Pattern. and John Vlissides. Prototype Pattern Structural patterns (7): Adapter Pattern.. Mediator Pattern. Interpreter Pattern.[edit] Design patterns Challenges of object-oriented design are addressed by several methodologies. As of April 2007. and thus to infer that objects instantiated from subclasses can always be safely used instead of those instantiated from the superclass. Facade Pattern. Flyweight Pattern. Abstract Factory Pattern. Some of these commonly occurring problems have implications and solutions particular to object-oriented development. Strategy Pattern. The book describes the following patterns: • • • Creational patterns (5): Factory Method Pattern. it describes 23 common programming problems and patterns for solving them. Template Method Pattern. More broadly. Visitor Pattern [edit] Object-orientation and databases Main articles: Object-Relational impedance mismatch. Builder Pattern. and Object database Both object-oriented programming and relational database management systems (RDBMSs) are extremely common in software today. Command Pattern. Composite Pattern. Subtype polymorphism as enforced by the type checker in OOP languages (with mutable objects) cannot guarantee behavioral subtyping in any context. Bridge Pattern. the term "design patterns" can be used to refer to any general. Observer Pattern. the book was in its 36th printing. Behavioral subtyping is undecidable in general. sometimes casually called the "Gang of Four". repeatable solution to a commonly occurring problem in software design. Class or object hierarchies need to be carefully designed considering possible incorrect uses that cannot be detected syntactically. The problem of bridging object-oriented programming . Iterator Pattern. This issue is known as the Liskov substitution principle. so it cannot be implemented by a program (compiler). Since relational databases don't store objects directly (though some RDBMSs have object-oriented features to approximate this). State Pattern. [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. Most common is known as the design patterns codified by Gamma et al. This intuition is unfortunately false in most OOP languages. Richard Helm. Ralph Johnson. [edit] Inheritance and behavioral subtyping See also: Object oriented design It is intuitive to assume that inheritance creates a semantic "is a" relationship. Along with exploring the capabilities and pitfalls of object-oriented programming.

where classes are defined around the datastructures that must be held. At the same time. but no general solution without downsides. The conditions under which OOP prevails over alternative techniques (and vice-versa) often remain unstated by . There are also object databases that can be used to replace RDBMSs.[19] One of the most common approaches is object-relational mapping. However.accesses and data patterns with relational databases is known as Object-Relational impedance mismatch. 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. 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.[24] Transparent representation of the control flow had no priority and was meant to be handled by a compiler. or even to engineer from the start.[25][26][27] [edit] Responsibility vs. as found in libraries like Java Data Objects and Ruby on Rails' ActiveRecord.g.[23] [edit] OOP and control flow OOP was developed to increase the reusability and maintainability of source code. "Good Ideas through the Looking Glass". a class should be defined around a responsibility and the information that it shares. some principal limitations of OOP had been noted. data-driven design Responsibility-driven design defines classes in terms of a contract. There are a number of approaches to cope with this problem.[21] An example for a real world problem that cannot be modeled elegantly with OOP techniques is the Circle-ellipse problem. However.[22] This limitation may lead for some real world modelling to overcomplicated results compared e. OOP was even invented for the purpose of physical modeling in the Simula 67 language. that is.g. to procedural approaches. This is contrasted by WirfsBrock and Wilkerson with data-driven design. and it is therefore well suited to model complex systems with complex behaviours" (contrast KISS principle). 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. "This paradigm closely reflects the structure of systems 'in the real world'. or is even a worthy goal. However. [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. The authors hold that responsibility-driven design is preferable. [edit] Matching real world OOP can be used to translate from real-world phenomena to program elements (and vice versa). a significant number of engineers feel the reverse may be true: that software becomes more complex to maintain and document. but these have not been as technically and commercially successful as RDBMSs. "Reality is a cousin twice removed". document and maintain. something hard to achieve with OOP. it was also noted (e. However. not everyone agrees that direct real-world mapping is facilitated by OOP (see Criticisms section). developer transparent control flow becomes more important. With the increasing relevance of parallel hardware and multithreaded coding.

.[34] Joe Armstrong. A number of well-known researchers and programmers have analysed the utility of OOP. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. Christopher J."[35] Richard Mansfield.[28] Richard Stallman wrote in 1995.[31] Date and Darwen[32] propose a theoretical foundation on OOP that uses OOP as a kind of customizable type system to support RDBMS. however. is difficult because of lack of an agreed-upon and rigorous definition of OOP. Date stated that critical comparison of OOP to other technologies. author and former editor of COMPUTE! magazine. I used OOP when working on the Lisp Machine window systems. This is at the expense of slowing down productive programmers who know how to use more powerful and more compact techniques.[30] has shown no significant difference in productivity between OOP and procedural approaches. making rational discussion of the topic difficult. Alexander Stepanov suggested that OOP provides a mathematically-limited viewpoint and called it "almost as much of a hoax as Artificial Intelligence. committed to OOP and nothing but OOP for the rest of their lives. what going through airport security is to flying". creator of Clojure. communism. I am unfair to AI: I learned a lot of stuff from the MIT AI Lab crowd. described object systems as over simplistic models of the real world.". relational in particular. OOP may well prove to be a durable delusion. In a sense. I have yet to see an interesting piece of code that comes from these OO people.. and often leading to heated debates[citation needed] over the matter. "Adding OOP to Emacs is not clearly an improvement. the principal inventor of Erlang."[36] He also is quoted as saying "OOP is to writing a program.[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". they have done some really fundamental work.[37] Rich Hickey.[ . and so on—history is littered with them). Here is an incomplete list: • • • • • • • • • Luca Cardelli wrote a paper titled "Bad Engineering Properties of Object-Oriented Languages". Entire generations of indoctrinated programmers continue to march out of the academy. He emphasized the inability of OOP to model time properly. states that "like countless other intellectual fads over the years ("relevance". is quoted as saying "The problem with object-oriented languages is they've got all this implicit environment that they carry around with them."[29] A study by Potok et al.either party. OOP will be with us until eventually reality asserts itself. and I disagree with the usual view that it is a superior way to program. But considering how OOP currently pervades both universities and workplaces. "modernism". which is getting increasingly problematic as software systems become more concurrent..

Obviously no one will distribute a Hello World class. the advantage is. Now try this. which means you have to create a copy of it. This is what everyone uses. type in MyHelloWorldClass followed by a dot. Remember. Go to the solution explorer(on your right). For example if you delete this line and go to Form1_Load. Classes are useful because they can be reused. you dont have to type anything over again. The collision detection class(which we will. our class name is HelloWorld. This tutorial will cover very basic OOP so that we can move on into the animation tutorial. once you make it. When you add the item select class. type in HelloWorld followed by a dot. you could put those subs in a class. For example. take the code above. This question will come up every time: why NEW? . Here's how you use a class. and use it for every level in your game to check for collision detection. Add this sub: Public Sub SayHelloWorld() MessageBox. Go back to Form1. You have to dim it as your class in order to use it. If you give this Hello World class to someone else. this concept might be a little tricky.OOP OOP . subs.. you'd have to instantiate it. Go back to the HelloWorld class.vbProgramming Tutorials . YOu wont get a popup box that has SayHelloWorld in it. In form1_load. Dim MyHelloWorldClass As New HelloWorld() We have to Dim something as the class. Starting Up Create a project called OOP. and name it HelloWorld(hmm. VB. Once you understand the concept you'll see why its extremely useful when programming.Object Oriented Programming. but if you made a whole bunch of subs that checked collision detection for your game. You don't need to make any modifications at all. You wont get any popup boxes. let's say we make a Hello World class. I wonder what this program is going to do). you'll notice that it says: Public Class Form1 End Class A class is basically a file which contains variables. Right click where it says "OOP"(right above where it says "References".Show("Hello World") End Sub This sub obviously displays "Hello World" in a MessageBox when you call it. make in another tutorial) can be used for every level(or every form) without any exceptions.NET automatically generates this code for you: Public Class HelloWorld End Class Well if you go back to where it says Form1. and you tell them to use it. In order to use the class. You'll see what classes are in a moment. as long as you program it properly. and go to Add | Add New Item. their program will display hello world too. and type it in without the New. in fact. and functions that do something.

you'll notice that SayHelloWorld is missing." The explanation follows: Many people use a cookie analogy to describe the relationship of a class and an object. go to form1_load and type in MyHelloWorldClass followed by a dot. and THEN take notes on it. You can use the same cookie cutter to make various kinds of cookies.Show("Hello World") :-). Go to your HelloWorld class. you wouldnt! Its an important artifact. it's going to the sub SayHelloWorld. if you take notes on it. If you go to form1_load and type in MyHelloWorldClass. are the properties of the object. Thanks Stipto! --OK. I know. run your program and obviously you'll get a messagebox that shows HelloWorld.. In form1_load. you instantiate an object of the cookie class. Let's get moving on to some advanced stuff.. In the same manner. and there's no reason to distribute it because anyone can type MessageBox. this was just to demonstrate basic OOP. In the sub. As you're typing the dot. and from that Sub Hi. some may be frosted or have colored sprinkles on top. such as flavor and topping. Well. and then use the copied class. delete the line MyHelloWorldClass. For now. type in SayHelloWorld(). you might ask.When you make a cookie using a cookie cutter. and you come across an important document. create a Public Sub Hi in the class. you don't want to use the original class. but you can use it to make cookies. What we're going to do in this 2nd part of the tutorial is learning about Constructors. What's happening is it's going to the sub Hi. Some Adcanced Stuff The program which we just did was completely useless. you can use it within the class . Change the Public Sub SayHelloWorld to a Private sub. but I couldnt think of anything else)! So basically. If you're a historian. "Programming in Visual Basic .. Go back to form1_load and type in the line which you just deleted.Think about it this way. it'll display hello world. Although all the cookies will have the same shape.. That's the simplest class you'll ever use in your entire life :-D. He got it from his book. others are lemon or vanilla. The characteristics of the cookie.it's not that useful in this program but i'll show you uses for it in other programs. You can't eat a cookie cutter.NET by Julia Case Bradley and Anita C Millspaugh. post it at the forums) --Note: 'Stipto' emailed me an alternate explanation for this. or draw on it or something like that. that's becuase it's private. now that you have the "New" there.SayHelloWorld() line. you have to take a photocopy of it. and click the box that says "SayHelloWorld". . some may be chocolate. The cookie cutter is the class. it might get ruined (this is THE dumbest story. "Well why would you want it to be private if you can't use it in the form".Hi. the cookie is the object. (bad explanation o_O . and you (for some strange reason :-p) want to take notes on it. Easy enough. you want to create a copy of it by saying New.if anyone can think of anything better.

Instead of saying Form1.) 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 . 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. Me! Dim Change As New ChangeBackground(Me) Even if you create another form.BackColor = Color. 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. We'll learn about that in another tutorial) We pass in an argument called Target. The "Advanced OOP" tutorial will teach you Inheritance. ByVal YourColor As Color) target. How do we make it so that we change the background color to ANY color we want? Simple.backcolor = color. there's 2 things. This tutorial is a relatively simple one. etc. byVal and byRef.Red End Sub (Note: the "ByVal" is automatically typed in.BackColor = YourColor End Sub Now go back to your Globals area for Form1.What is a constructor? A constructor is something that is called when you instantiate(make NEW) an object. Public Sub New(ByVal target As Form. when we Dim MyHelloWorldClass as New HelloWorld. Type this in: Dim Change As New ChangeBackground(Me. but every time I push 'enter'.Blue) Run your program and it changes the background color to blue. we specify an argument called Target which can be used for any form. especially a form. Go to form1's code. dreamweaver changes it back.Forms.Windows. you get the message.red. Color. a little popup box tells you "Target As System. A constructor is in the sub New of your class. it just changes the background color of the specified form to red. and rename sub Hi to sub New. PolyMorphism. this will change the background color for every form. Create a new class called ChangeBackground... We know what this does. meaning that you have to specify a form. Create this sub: Public Sub New(ByVal target As Form) target. pass in a color argument.. If we took that HelloWorld class. Destructors. We're going to make a class that changes the background color of the form with the color you specify.. we would just say.. In order to refer to form1. Since we dimmed it in the globals (at the top of your code). Delete your HelloWorld class (right click it in the solution explorer and hit delete. Type this in: Dim Change As New ChangeBackground( While you're typing in the parenthesees. and your background color will be Red.Form". which is our form. Run your project. just to give you an introduction to OOP.

.

You can download the .Learning a new way of programming is no different.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. Next: Objects. it requires a new way of thinking. The tutorial has some examples in C++. • • • • • Objects Objects are the central idea behind OOP. you can download the free JBuilder Foundation from Borland C# is a relatively new language developed by Microsoft. There are a number of OOP based languages out there. The idea is quite simple. . The best way to learn any language is to practice . examples using Modula-2 will also be used . The idea is to not primarily concentrate on the cornerstones of procedural languages .data structures and algorithms . It was aimed at students moving from a procedural Pascal type language (Modula-2) to Object Oriented programming. You can start playing with these languages straight away . If you want to have a complete development environment. OOP is more than learning a new language. although examples in C++ and Java will be given. It's designed for students who have some knowledge of procedural programming. but for beginners I would recommend starting with either Java or C# (pronounced CSharp). however I don't recommend starting to learn OOP in C++.NET SDK which contains a C# compiler. To compare OOP with procedural languages.Academic editions are available. If you want to develop in C# seriously. Java is a platform-independent language developed by Sun Microsystems.free compilers and development environments are available. syntax. Since then many people have found the tutorial useful so it has been slightly updated and remains on the site. 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. You can pick up the Java SDK and begin developing straight away.Modula-2 is from the Pascal family of languages so hopefully should be familiar to most students. you'll need to get hold of Microsoft Visual Studio . Belfast. It is not tailored to any one specific language. C# is one language that forms part of Microsoft's .but instead think in terms of objects. etc. Table of Contents • • • • • • • Introduction Objects Classes Inheritance Conclusion Introduction This tutorial aims to teach the basics of Object Oriented Programming.NET platform.

An object is a bundle of variables and related methods. END.. a program should be written to simulate the states and activities of real world objects. we turn to any student's favourite pastime.1. . This is however.. . PintsNeededToGetYouDrunk: CARDINAL.. Now lets say we want to initialise a pint of beer.. Proof: REAL. First. MyPint.. A few examples should help explain this concept. you will remember that we must not only deal with data types. . and gave that structure various names.BeerName := "Harp"..VolumeInPints := 1. VolumeInPints: REAL. we might code this as: VAR MyPint: BeerType. in other words. This means that apart from looking at data structures when modelling an object.. (* Initialise (i. but we must also deal with methods.e.VolumeInPints . If we were writing this program in Modula-2. we could write something like this: TYPE BeerType = RECORD BeerName: STRING. Most programs are written with very little reference to the real world objects the program is designed to work with. .0. A method is an operation which can modify an objects behaviour. and take a sip from it.. (* Take a sip *) MyPint. buy) a pint: *) MyPint.. In other words. If you remember how we defined an object at the start of this section. that is we defined BeerType as a record structure. .00.VolumeInPints := MyPint. we'll come back to these later. This is the norm for procedural programming.g. in object oriented methodology. BEGIN . In Modula-2. Colour: ColourType. A method is similar to a procedure... it is something that will change an object by manipulating its variables. we must also look at methods associated with that object.. Name. Drink! Say we want to write a program about a pint of beer. We have constructed this entire model based entirely on data types. The basic idea behind an object is that of simulation. e. not how we look at things when we want to program using objects. functions that modify the objects attributes.

for quick pints. a volume. 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. Another Example We'll now deal with a real-life example which will help us understand some more object concepts. but we'll cover them much later. we cannot directly modify BeerType's variables .. in this case a pint of beer. but also all possible operations that we might want to perform on that data. We must use the object's methods to do this. 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. etc. What this means in our example is that unlike the Modula code. when we want to model it using computational objects. Now the important bit from this section: Only an object's methods should modify its variables There are a few exceptions. we can only take a sip. what this means is that we must think very carefully when we define methods. PROCEDURE GetCounterValue(): INTEGER. In practice..for post exam pints. If you don't know that then you shouldn't be reading this! To make things very simple. Sink_Pint . . GetVolume . An object variable is a single variable from an object's data structure. Take_A_Gulp . we nearly can: DEFINITION MODULE Counter. for example BeerName is one of BeerType's object variables. we cannot do this with the above definition. a gulp etc. say Take_Drink which will take a parameter representing the amount of beer we wish to drink. We must go back and define a new method associated with BeerType. PROCEDURE IncrementCounter. There are loads more methods we could define . when we come to implement the above using objects we will define three methods that do the above.This means that when we take a real world object. some definitions. 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. Now.this should allow us to give our beer a name.. A counter is a variable in a program that is used to hold a value. PROCEDURE InitialiseCounter(InitialValue: INTEGER).to see how much beer we have left! Take_A_Sip . We will design an object to emulate a counter.we might want a function GetBeerName to help us order another pint for example.we cannot set BeerName to "Guinness" directly. we should also define the following methods associated with the BeerType object: • • • • • InitialiseBeer ..for lunchtime pints. Well.. we not only look at the data structure that it consists of. For our example..

as we'll see. PROCEDURE GetCounterValue(): INTEGER. A class can be considered to be an extremely extended TYPE declaration. all of the above discussion has nothing to do with the behaviour of the counter itself. END GetCounterValue. When programming with objects we can ignore anything not directly concerning the behaviour or state of an object. we cannot directly access MyCounter from any module that imports Counter. Perhaps in our Modula-2 program we need three counters. We could define an array of MyCounter and work through that. BEGIN INC(MyCounter). we instead turn our attention to classes. BEGIN MyCounter := 0. A class is a blueprint for an object. But being object oriented means a lot more than just encapsulation. A class does not represent an object.encapsulation. This blueprint is valid whether we have one or one thousand such objects. PROCEDURE IncrementCounter. . Because Modula-2 is not object oriented. END Counter. The point of all this is that we are talking in terms of data structures. or an outline of an object. but that would waste a lot of memory if we only used a few counters. BEGIN RETURN MyCounter. VAR MyCounter: INTEGER.e. Classes Say we wanted to extend the counter example discussed previously. this will only satisfy one of the requirements for an object oriented language . Next: Classes. IMPLEMENTATION MODULE Counter. PROCEDURE InitialiseCounter(InitialValue: INTEGER). Perhaps if we needed an infinite amount of counters we could put them in a linked list and allocate memory as required. What this basically means is that we provide a blueprint. Or say we needed up to 1000 counters. END IncrementCounter. since not only are variables held but methods too. This simply means that we have implemented information hiding.. i.. Then we could also declare an array. BEGIN MyCounter := InitialValue.END Counter. it represents all the information a typical object should have as well as all the methods it should have. END InitialiseCounter.

You really need to understand the fundamentals of C before the example will make any sense. these will not be accessible to the outside world but only within the class declaration. as the name suggests. These methods.e. This method is called the class constructor. This is encapsulation. that is they cannot be accessed from outside the class declaration. We can now . The methods are implemented as C++ functions or procedures. this is much more. Functions and procedures can also be placed in the private section. To create an object that simulates a counter in C++ then. all we have to do is declare in our main program: Counter i. a specification for our object. The public section contains all the object's methods. Instantiation This is an awful big word for a powerfully simple concept. the three methods should be easy to understand. Although this seems just like an ordinary variable declaration. These define the state of the object. The methods are the only means of communication with the object. All we have done so far is to create a class. As the name suggests. All class definitions should also have one public method that has the same name as the class itself.C++ As an example. The variable i now represents an instance of the counter type. in this case Counter. and will be explained soon. This can be used to provide support routines to the public routines. class Counter { private: int MyCounter public: Counter() { MyCounter = 0. } { { } A lot to go through for this little example. • • • • • In the private section. a counter object. i. the variables are going to be private. all the objects variables should be placed. we have not created our object yet. } void InitialiseCounter(int value) MyCounter = value. } void IncrementCounter() MyCounter++. lets give the C++ class definition for our counter object. } int GetCounterValue() { return (MyCounter). can be accessed outside the class declaration.

for example we can set the counter to the value '50' by calling i.communicate with this object by calling its methods. This defines the superclass. This method should contain any start-up code for the object. Should we need 1000 counter objects we could declare an array of counter objects: Counter loads[1000].InitialiseCounter(50). say: Counter j.and we can get the counter value . Although the new counter shares the same blueprint as the previous object.GetCounterValue(). It is remarkably similar to the C++ definition. } public void IncrementCounter(void) MyCounter++.int value = i. when we first declare.InitialiseCounter(). What this means is that i and j are two distinct objects. } { { { { } A few brief notes about the differences: • All new classes must be defined with the extension extends Object. When we first instantiate an object (i. each with their own separate values. this will be dealt with in the next section. any initialisation of object variables should appear within this method. the class constructor is called. All we have to do is declare a new object. Remember the question posed at the very start? The power of objects starts to kick in now. or create it).IncrementCounter(). We can increment them independently.. Counter() { MyCounter = 0.. Java The equivalent Java class definition for the counter example follows. } public int GetCounterValue(void) return (MyCounter). . it shares none of the same data.. The class constructor is the method with the same name as the class definition. for example. the first thing that happens to the object is that the variable MyCounter is initialised to zero. . In the counter example. class Counter extends Object private int MyCounter. and differs only in syntax. We can increment the counter i.e. Say we require another counter within our program. whenever we create a new counter object. and then initialize one of them using a call such as loads[321]. } public void InitialiseCounter(int value) MyCounter = value.

but for larger projects. The class constructor definition remains the same. Then we actually create an instance of the object by a call to new in the second line. Modularity: Different programmers or teams can work on different independent objects. objects are declared differently: Counter i. FrenchBeerType which had all the variables and methods of BeerType plus the few extra we needed. we can define FrenchBeerType to be a subclass of BeerType. Basically we define a variable to reference the object in the first line. Accessing object methods is done in the exact same way in Java as in C++. instead all variables and methods are prefixed with the appropriate public or private qualifier. To help explain inheritance. it's difficult to see from such a small example. 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. Say we want to define a new class to represent a pint of an imported French beer. so why bother? Well. i = new Counter(). Instead. Why Bother? The process of designing and programming objects seems very cumbersome. . OOP is used for the following reasons. we'll go back to our beer example. • • • Encapsulation: in our example we cannot alter the value of the counter other than by incrementing it or setting it to a initial value. everyone knows the price of Harp. What this means is that we only need to define the additional information that the FrenchBeerType class has. This drastically helps with understanding of the code and eliminating potential bugs. Next: Inheritance. Inheritance: this is covered in the next section. This class would have all the variables and methods of the normal beer class.• • There are no public or private sections. 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. Inheritance Another big word for a simple concept. A subclass is a class definition which derives functionality from another class definition. Instantiating objects in Java is slightly different. OOP techniques allow a great deal of flexibility.

and i.. 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. If we go back to how the class was defined: . This means that if we instantiate a ReverseCounter object. Counters. so we could be forgiven for breaking this rule. Inheritance is a powerful tool. In Java. if i is an object of the ReverseCounter class. that is a subclass of ReverseCounter which could provide added variables or methods. For example. we can use any method that the class Counter provided.. bugs. Bugs. A superclass is the "parent" of a subclass. We are simply saying that we want ReverseCounter to be a subclass of Counter. i. In the class definition. If you tried to compile the above example and found it wasn't compiling. and tell our compiler that it is a subclass of BeerType.. 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. we'll define a new class ReverseCounter that is a subclass of Counter. Unlike our simple example. don't worry! There is a semi-deliberate mistake left in the code. then we can both increment it and decrement it. This means that FrenchBeerType has all the attributes of BeerType plus a few additional ones. once again would be mad to define a brand new class with everything that Counter has plus a new method.So.. as well as the new methods provided. All this talk of beer. inheritance can be passed on from generation to generation. We have defined ReverseCounter to be a subclass of Counter. so if we were defining this in Java we would use class FrenchBeerType extends BeerType. respectively. But say in a program we require a counter that can not only be incremented. When we defined the Counter class we didn't even know what a subclass was. Instead. in our beer analogy. Back to the counter example then! The counter we had in the last section is fine for most counting purposes. } } { The extends clause indicates the superclass of a class definition.. all this is automatically inherited. which I am very usefully going to use to stress a point. we create a new class. Counters. class ReverseCounter extends Counter { public void DecrementCounter(void) MyCounter--. but can be decremented too.DecrementCounter. We'll do this in Java. BeerType is the superclass of FrenchBeerType. FrenchBeerType. bugs.IncrementCounter(). When defining a class you must consider subclasses.. Counters. Since this new counter is so similar in behaviour to our previous counter. we could define a class SuperDuperReverseCounter for example.

hopefully you found the tutorial to be of some use.. Johnson. Vlissides ISBN: 0-201-63361-2 Describes Patterns. It is not available to any other class. Next: Conclusion. This is appropriate in this case. advanced Object Oriented programming solutions to common problems. 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. . since we don't have access to that variable. as well as all subclasses of this class. { } We can see that the variable MyCounter is defined to be of type private.class Counter extends Object private int MyCounter. . very private indeed. You can use this book while learning any of the above languages. Design Patterns. 2nd Edition Patrick Niemeyer.. So when we reference MyCounter from inside the ReverseCounter the Java compiler will kick up a fuss. this means that the variable becomes very. Accelerated C++ Andrew Koenig. Learning Java. 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. In Java.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. To fix this. We should have realised at the time of writing the Counter class that subclasses might need to get at this variable too.. Barbara Moo ISBN: 0-201-70353-X A great beginners guide to programming in C++. This tutorial only begins to explain OOP though . including its derived classes. . Elements of Reusable OO Software Gamma.. A variable with a protected qualifier means that it can be accessed from within the class in which it is defined. Helm. all we have to do is change the definition of MyCounter to: protected int MyCounter. in fact. Conclusion Congratulations if you made it this far . it is only accessible from inside the class from which it is defined. Almost all of the books from O'Reilly are worth reading.

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. Here we skim the vital concepts and show some code samples that may be of use as you learn. each object knows what information describes itself and what actions it can perform with that information. Controls needed: N/A Level: All What is Object Oriented Programming? Object Oriented Programming allows developers to mimic real world items and concepts.As I said at the start of this tutorial. Good luck! Plee support our sponsor: Please support our sponsor: Best New Cars Online. In an OOP world.! 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.! Best New Cars Online. The class ... check out his VBJones Web Site.. the best way to learn OOP is by practice . 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... OOP allows developers to create reusable objects that interact with each other to form complex entities. Many thanks to Derrick for graciously providing this tutorial..

readable.2b : An Object Which Exposes Public Methods . A Class is generally considered to be a "Black Box". In Visual Basic you can create any number of "Object Variables" from a single Class Definition. which are used to store information the object requires to perform its task(s). Programmers generally create a Class for each separate entity used within their application. you can use the object created from a Class without knowing how the internal code works. Figure 1. reusable code. not seen by users. Each data item is called an "Attribute" in OOP. Each object can have internal variables. Properties are exposed through the Public Interface of an object. That is. Once again only those Methods exposed by the Public Interface are available to outside users.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. Objects = Attributes + Actions An object is an "Instance" of a Class. Each object knows what data describes it and how to manipluate that data.2a : An Object Which Exposes Public Properties VERSION 1. Classes allow developers to write modifiable.These functions and procedures are called Methods in OOP.definition is used to create "Instances" of the class. All the developer needs to know is which methods to call to perform certain functions. which are the actual objects used within your application. How those functions perform their tasks is hidden. Visual Basic implements these attributes as "Properties". Figure 1.

VERSION 1. Lesson 2] OOP:Object Oriented Programming Name: Understanding OOP Author: Derrick Mead Date: 8/18/97 Lesson: 2 .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 .

Visual Basic provides a modified version of Inheritance commonly termed Containment. How an object performs its tasks is of no concern to the developer using the object. Figure 3. become its' attributes. 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. Any properties and methods from one class are then automatically available as properties and methods of the new class.1a : C++ directly uses Person.Encapsulation One of the fundamental concepts of OOP is the method with which objects store and manipulate data known as Encapsulation.Name when Student. It is essentially a "Black Box". Figure 3. a set of Public Properties and Methods which the object exposes to the outside. Let's look at how you would code this : . objects can be created from other objects. This is called Inheritance.Name is called. A Method can be used internally or exposed to the programmer. Inheritance In the pure world of OOP. the data that is input and output from the object. A comparison is the best way of explaining this concept. when exposed to outside world. In addition to knowing what data to deal with. Functions and Procedures that perform tasks are called Methods.Name is called. VB defines these exposed attributes as Properties.Name when Student. Each object consists of internal variables which. The developer communicates and controls the object via the Public Interface.1b : VB must explicitly call Person. If a Method is declared as Private then it can only be used inside the object. The outside world does not see it. That is. each object knows how to manipulate that data.

4% for all sales over $200.05 Public function CalcTaxes ( curTaxableValue as Currency) as Currency CalcTaxes = iTaxRate * curTaxableValue .6% up to $200. the ability to change the behaviour of a class based upon certain criteria. Then create a class which references both the previous objects. Some objects provide the functionality of several different objects with similar behaviours. We can create an object class which performs the calculation for Region A.Name = sNewName End Property Public Property Get Name ( ) as String 'retreive the person objects Name Property Name = oPerson. Region A calculates Sales Tax at a flat 5% of the Sales Total. Region B calculates Sales Tax on a prorated basis . This is Polymorphism. Here's the code for this example : 'Class : clsTaxRegionA Const iTaxRate = . When you wish to calculate taxes just tell your Wrapper Class which region to use and the proper calculations are performed. Lets look at an example : Two geographic areas have different methods to calculate Sales Tax.Name End Property Polymorphism Objects can be as complex as you desire to make them. and another class for Region B.'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.

Lesson 2] .CalcTaxes (curTaxableValue) end if End Function [Lesson 1 .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.End Function 'Class : clsTaxRegionB Const iTaxRate1 = .06 Const iTaxRate2 = .

What is the Conclusion? 6. though the ratings for the articles are not. Why Architecture is important? o 4.20. What is the difference between an Interface and an Abstract class? o 4. What is Implicit and Explicit Interface Implementations? o 4.5.1. What is the Data Access Layer? o 4. What is an Abstract class? o 4. What is the difference between Abstract Factory and Builder design patterns? 5. Introduction I have noticed an increase in the number of articles published in the Architect category in code-project during the last few months.29. What is Abstraction and Generalization? o 4. What is Operator overloading? o 4. What is a Class? o 4. What is an Interface? o 4.17. What is Association? o 4.24. 3. What is Method Overriding? o 4. What is OOP? o 4. What is three-tier architecture? o 4. What is the Business Logic Layer? o 4. What is a Class Diagram? o 4.18.31.28. • • • Introduction Background Prerequisites The Main Content o 4. What is the difference between a Class and an Interface? o 4. What is Method Overloading? o 4.4. How to identify and design a Class? o 4. What is the difference between Association. What is Software Architecture? o 4.6.25. What is SOA? o 4. What is two-tier architecture? o 4.15.2. What I Referred? 7.22. What is an Object? o 4.Introduction to Object Oriented Programming Concepts (OOP) and More • • • • 1.32.8. What is a Package Diagram? o 4.27.26.9.14. Aggregation and Composition? o 4.30.11.10. What is a Use case? o 4.13. History 1. but the quality does not match their expectations.7.19.23. This indicates that readers are interested in reading articles on Architecture. What is Gang of Four (GoF) Design Patterns? o 4. The number of readers for most of these articles is also high. What is Encapsulation (or information hiding)? o 4.3. What is MVC architecture? o 4. 4. 2. This article is a constructive attempt . What is Inheritance? o 4.21. What is Polymorphism? o 4. What is a Sequence Diagram? o 4.16.12.

know it right. I noticed that there is a knowledge gap. You will feel that an interface needs to be defined for every class. it is an unbalanced distribution of knowledge. and also referred to the same resource set you all read. I myself am no exception and am a result of this very same system. It also said that the richest 1 percent of adults owned 40 percent of global assets in the year 2000. understands the meaning. know nothing. on basics of software architecture. The new developers are trained to use (I would say more often) already developed software components. that the richest 10 percent of adults accounted for 85 percent of the world's total wealth. The one. It is like that. But the sad part of the story is. and implement such components. the massive expansion of the software industry is forcing developers to use already implemented libraries. 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. like I did once. services and frameworks to develop software within ever shorter periods of time. The bottom line is that only a small percentage of developers know how to design a truly object oriented system. but still developers struggle to understand the basic concepts. So they say. you need to have experience to get a job. As the number of years pass by. There are some good articles out there. but the old legacy of not understanding. newcomers will always struggle to understand a precise definition of a new concept. who know. Unfortunately. As I see it. creating a vacuum of good architects. Background This article began after reading and hearing the questions new developers have. between the architects who know how to architect a system properly and the others who do not know. animals and many other physical world entities to teach concepts of software architecture. may laugh at you and say that the way you have designed it is wrong. I got the same education that all of you did. increasing every day. irrelevant examples of shapes. One day I read an article that said that the richest 2 percent own half the world's wealth. You will find it harder to understand when and when not to do something.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. . But the ones. They just plug in an existing library and some how manage to achieve the requirements. The most of them use impractical. Just like the world’s wealth distribution. to complete the development quicker. these developers become leads and also software architects. but the one who doesn’t. because it is always a new and hence unfamiliar idea. 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. So there is an unbalanced distribution of wealth in the physical world. of not having any architectural experience continues. Just prepare to go through a painful process. 2. The ones. There are only very few good business-oriented design references. And further. Others will criticize you. I hope that this article will give you the right start for that long journey. and learn continuously. who do not know. you will try to apply everything you know or learned from everywhere. struggles to understand the very same definition. and more importantly. Coming back to the initial point. the start with software architecture is no exception. that they never get a training to define. Employers want experienced employees. Their titles change. It will be difficult. When you start to design your very first system. the way to apply them correctly. who has experience. In this process you will also have to read and think a lot. Listen to them. and also the related online teaching materials are either complex or less practical or sometimes even wrong. Have you ever thought of an unbalanced distribution of knowledge in the software world? According to my view point. design the architecture for.

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. this article is for you. and a continual study of antiquity” – I read this phrase when I was reading the book named “The Art of War”. The Main Content 4. . 4. Why Architecture is important? The primary goal of software architecture is to define the non-functional requirements of a system and define the environment. to step-in to the next level to become a software architect. isn’t it? 3. 4. Architecture is important because it: • • • • • Controls complexity Enforces best practices Gives consistency and uniformity Increases predictability Enables re-use. focusing on Object Oriented Programming (OOP).“The knowledge of the actions of great men. Prerequisites This article is an effort to provide an accurate information pool for new developers on the basics of software architecture. acquired by long experience in contemporary affairs. who has a minimum of three or more years of continuous development experience and has that hunger to learn more.1. seems applicable here.2. techniques and tools. If you are a developer. The detailed design is followed by a definition of how to deliver the functional behavior within the architectural rules. What is Software Architecture? Software Architecture is defined to be the rules.

4.). the hand can grip something or a Student (object) can give the name or address. etc. What is a Class? A class is simply a representation of a type of object. What is an Object? An object can be considered a "thing" that can perform a set of related activities. all of the same . The set of activities that the object performs defines the object's behavior. In pure OOP terms an object is an instance of a class. there may be thousands of other bicycles in existence. 4. It stands for Object Oriented Programming. named left hand and right hand.3. In real world. Collapse Collapse Student objectStudent = new Student(). Hence. Collapse Collapse public class Student { } According to the sample given below we can say that the student object. What is OOP? OOP is a design philosophy. and operations. named objectStudent. ObjectOriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C. So the shoulder is an interface which your body uses to interact with your hands. The “hand” is a class. you'll often find many individual objects all of the same kind. Class is composed of three things: a name. attributes. Pascal. let’s take your “hand” as an example. 4.5. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface).4. Everything in OOP is grouped as self sustainable "objects". Your body has two objects of type hand. you gain re-usability by means of four main object-oriented programming concepts. For example. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. The hand is a well architected class. A class is the blueprint from which the individual objects are created. has created out of the Student class. It is the blueprint/ plan/ template that describe the details of an object. In order to clearly understand the object orientation. As an example.

they are called four main Object Oriented Programming (OOP) Concepts. you need to identify the full list of leaf level functions/ operations of the system (granular level use cases of the system). if you start analyzing a full system at the start.7. Then you can proceed to group each function to form classes (classes will group same types of functions/ operations). the methods and the data. However according to Object Oriented Design Principles. 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. without modifying it. you will find it harder to manage. you have already used classes. and only one. • • • • • SRP . reason to change. In OOP the . Each bicycle has built from the same blueprint. please refer to Object Mentor.The Single Responsibility Principle A class should have one. and to reduce the complexity. Abstraction. you are actually creating a new instance of the TextBox class. not on concretions. DIP . and Polymorphism.The Dependency Inversion PrincipleDepend on abstractions. In the software world. there are five principles that you must follow when design a class. In objectoriented terms. each designer uses different techniques to identify classes. OCP . the TextBox control. the system designers use several techniques. Additionally to identify a class correctly. For example. 4. Inheritance. which defines its appearance and capabilities. you need to have proper management policies in place. Same technique can be applies to manage classes of your software system as well. we say that the bicycle is an instance of the class of objects known as bicycles. when you have many. 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 . 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. is made out of the TextBox class.The Liskov Substitution PrincipleDerived classes must be substitutable for their base classes. How to identify and design a Class? This is an art.The Interface Segregation PrincipleMake fine grained interfaces that are client specific.The Open Closed Principle You should be able to extend a classes behavior.6. In order to manage such a work force. In order to manage the classes of a software system. A software system may consist of many classes. 4.make and model. For more information on design principles. though you may not have realized it. it needs to be managed.basically. ISP . These concepts are the four main gods of OOP world and in software term. Each time you drag a TextBox control. LSP . Think of a big organization. In software world the concept of dividing and conquering is always recommended. But in any case. with its work force exceeding several thousand employees (let’s take one employee as a one class). which can be grouped under four main concepts named Encapsulation. you always used.

encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. 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.8. Collapse Collapse public class StudentRegistrar { public StudentRegistrar (). In order to modularize/ define the functionality of a one class. and composition. According to Object Oriented Programming there are several techniques. There are several other ways that an encapsulation can be used. attribute and properties to provide its indented functionalities to other classes. that class can uses functions/ properties exposed by another class in many different ways. as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.Initialize(). classes can use to link with each other and they are named association. What is Association? Association is a (*a*) relationship between two classes.encapsulation is mainly achieved by creating classes. 4. That idea of encapsulation is to hide how a class does it but to allow requesting what to do. which encapsulate the set of methods. The class is kind of a container or capsule or a cell. aggregation. } } . { new RecordManager(). Collapse Collapse IStudent myStudent = new LocalStudent(). where as the aggregation and composition are relatively special. IStudent myStudent = new ForeignStudent(). localize implementing information through the IStudent interface. the classes expose public methods and properties. Association is the more general term that define the relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. In that sense.

Aggregation is the (*the*) relationship between two classes. aggregation always insists a direction. But even without a Chancellor a University can exists. Every one understands association. but with two other OOP concepts. all three concepts are closely related. Since a direction is explicitly specified. In that case we called that University is composed of Faculties. the life time of a Faculty (or Faculties) attached with the life time of the University . The aggregation or composition cannot be separately understood.9. Unlike association. association is a confusing concept. The troubles created not only by the association alone. and if you try to understand the composition alone it will always threaten the definition given for aggregation. hence must study together. before aggregation and composition are described. If you understand the aggregation alone it will crack the definition given for association.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. in this case the controller class is the StudentRegistrar. . What is the difference between Association. When object of one class has an (*has*) object of another. that is association. 4. Collapse Collapse public class University { private Chancellor universityChancellor = new Chancellor(). Aggregation and Composition? Association is a (*a*) relationship between two classes. Let’s explore all three and see whether we can understand the differences between these useful concepts. aggregation and composition. by comparing one definition to another. if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. If University is disposed the Faculties will not exist. But aggregation describes a special type of an association. where one class use another. } In this case I can say that University aggregate Chancellor or University has an (*has-a*) Chancellor. So that composition can be recognized as a special type of an aggregation. To some beginners. But the Faculties cannot exist without the University.

So the point is. there you have the Collection Element define inside (it is an inner part. If you take the . qualities and properties rather than the particulars (a suppression of detail). This way you are allowing the outer class to fulfill its purpose. parameterization.Net and Java uses the Composite relation to define their Collections. more accurate way is to have a one define inside the other class (making it a protected or private class). I have seen Composition is being used in many other ways too. Thus. The two mutually depend on each other. you can say that. if you want to bind two classes with Composite relation. However the more important factor. if you define the Collection and it’s Element to be independent. It places the emphasis on the similarities between objects. .Same way. we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. there is a composite relationship in-between a KeyValuePairCollection and a KeyValuePair. The life time of the two classes that has bond with a composite relation mutually depend on each other. as an example. It places the emphasis on what an object is or does rather than how it is represented or how it works. generics and polymorphism. that most people forget is the life time factor. So in summary. farcing the Element to get disposed with the Collection. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. (Association->Aggregation->Composition) 4. Programming languages provide generalization through variables.net Collection to understand this. The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. than a Composition. then the relationship would be more of a type Aggregation. While abstraction reduces complexity by hiding irrelevant detail. it helps to manage complexity by collecting individuals . hence called it is composed of) the Collection. Thus. generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. What is Abstraction and Generalization? Abstraction is an emphasis on the idea. while tying the lifetime of the inner class with the outer class.10. it is the primary means of managing complexity in large programs. Abstraction is essential in the construction of programs. as another example. If not.

Abstraction and generalization are often used together. As an example. /// inside the abstract class itself.Configure(). The name is used as a parameter.Config. . When the parameterized abstract is invoked. Please carefully read the comments as it will help you to understand the reasoning behind this code. Abstract classes are ideal when implementing frameworks. /// If you study carefully you will find a reason for not to have “set” method here. 4. cannot be instantiated. Abstracts are generalized through parameterization to provide greater utility.into groups and providing a representative which can be used to specify any individual of the group. // The additional initialization is done immediately after log4net. with the help of this technique the log can be made. } /// <summary> /// When you define the property as abstract.11. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. let’s study the abstract class named LoggerBase below.DOMConfigurator. Collapse Collapse public abstract class LoggerBase { /// <summary> /// field is private.LogPrefix).Type LogPrefix { get.LogManager. } /// <summary> /// Simple log method. irrespective of it origin. In parameterization. It can only be used as a super-class for other classes that extend the abstract class.ILog logger = null. so it only visible for inherited class /// </summary> protected LoggerBase() { // The private object is created inside the constructor logger = log4net. one or more parts of an entity are replaced with a name which is new to the entity.GetLogger(this. What is an Abstract class? Abstract classes. 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. /// </summary> protected abstract System. it is invoked with a binding of the parameter to an argument. which declared with the abstract keyword. so it intend to use inside the class only /// </summary> private log4net. /// it forces the inherited class to override the LogPrefix /// So. /// <summary> /// protected.

} } /// <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. Like any other class. It enforces and guarantees to have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class.logger. where a subclass can override it when required. hence. if a class is going to log an exception. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. The method named LogError is protected. which the exception has occurred) for every subclass. you wouldn’t have an idea about other modules of the system. By the time you define the LoggerBase. The abstract property named LogPrefix is an important one. hence I used a private field named logger declare the ILog interface of the famous log4net library. You are not allowed or rather you cannot make it public.IsErrorEnabled. In other word the LoggerBase provide a framework for exception logging. they have to inherit the LoggerBase. The access modifier of the constructor of the LoggerBase is protected. The virtual method may have its default implementation. before they invoke a method to log an error. will allow changing the source logger library easily. what to use. The public constructor has no use when the class is of type abstract. for logging. The abstract classes are not allowed to instantiate the class.Error(message). So I went for the protected constructor.IsErrorEnabled) { this. Apart from these you can also have virtual methods defined in an abstract class. without inheriting the LoggerBase cannot use it meaningfully.logger. an abstract class can contain fields. . This will allow the Loggerbase class to control.logger. as any class. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not./// which is only visible for inherited classes /// </summary> /// <param name="message"></param> protected void LogError(string message) { if (this. hence exposed to all subclasses. Let’s find out why the property named IsThisLogError is public. But you do have a concept in mind and that is. } } } The idea of having this class as an abstract is to define a framework for exception logging. Let’s try to understand each line of the above code.

Some say you should define all classes in terms of interfaces. } } 4. Collapse Collapse public interface ILogger { bool IsThisLogError { get.Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface. 4. Apart from that an interface is very useful when the implementation changes frequently.All and all. and this concept is very useful in cases where you need the implementation to be interchangeable. an object of such class can be encapsulated inside an interface. then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. If MyLogger is a class. 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. the important factor here is that all OOP concepts should be used carefully with reasons. What is an Interface? In summary the Interface separates the implementation and defines the structure.12. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface.13. which implements ILogger. you should be able to logically explain. while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). when architecting frameworks. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). but I think recommendation seems a bit extreme. What is the difference between a Class and an Interface? In . there we can write Collapse Collapse ILogger log = new MyLogger(). why you make a property a public or a field a private or a class an abstract. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two. If a class that implements an interface does not define all the methods of the interface. Interface definition begins with the keyword interface. The sample below will provide an interface for our LoggerBase abstract class. The two poses a clear separation from one to another. In addition to this an interfaces can inherit other interfaces. Additionally. A class and an interface are two different types (conceptually). An interface like that of an abstract class cannot be instantiated. Theoretically a class emphasis the idea of encapsulation. but it is .

4. but an abstract class lets your class admit that it doesn't know how to perform those actions. but can inherit only one class Abstract class must override all abstract method and may override virtual methods Interface can be used when the implementation is changing Abstract class can be used to provide some default behavior for a base class.15. even though both look similar. This approach allows the developers to develop the application within the guided help provided by the framework. Abstract classes let you define some behaviors. it can execute the method defined by the child class. Abstract class’s methods can have implementations and they have to be extended. Interface makes implementation interchangeable Interface increase security by hiding the implementation Abstract class can be used when implementing framework Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies. The base class knows that it needs those methods. When it is time to start up. but they have to be implemented. What is the difference between an Interface and an Abstract class? There are quite a big difference between an interface and an abstract class. the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by . the abstract class can call the startup method. if you have an application framework. What is Implicit and Explicit Interface Implementations? As mentioned before . it only knows that it must initiate the actions. For example. However. o o o o o o o o o o o o o o o Interface definition begins with a keyword interface so it is of type interface Abstract classes are declared with the abstract keyword so it is of type class Interface has no implementation.Net support multiple implementations.14. Interface can inherit more than one interfaces Abstract class can implement more than one interfaces. When the base class calls this method. Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static) Abstract class’s methods can’t have implementation only when declared abstract. such as startup and shutdown tasks etc. they force your subclasses to provide others. 4. 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. The abstract base class can declare virtual shutdown and startup methods. in practice when you come across with some application-specific functionality that only your application can perform.very useful and also meaningful to have a comparison between an interface and an abstract class.

Dispose() { Console.WriteLine("IDisposable. Let's consider the interfaces defined below.Dispose. exposing or preserving identities of each of interface methods.WriteLine("Student.Dispose").16. } void IDisposable. is called inheritance. What is Inheritance? Ability of a new class to be created. even when the method signatures are the same.hiding.Dispose"). } } 4. Collapse Collapse public class Exception { } . from an existing class by extending it. } Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable. Collapse Collapse interface IDisposable { void Dispose(). Collapse Collapse class Student : IDisposable { public void Dispose() { Console.

One of the most important relationships among objects in the real world is specialization. while IOException and SecurityException specialize with their characteristics and behaviors. In OOP the polymorphisms is achieved by using many different techniques named method overloading. which is called the base class or super-class. As such. has hair). A SecurityException is also an Exception. we expect it to share certain characteristics with the dog that are generalized in Mammal. I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts. They have all characteristics and behaviors of an Exception. . More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things. Similarly. At times. It has all the characteristics of any mammal (it bears live young. What is Polymorphisms? Polymorphisms is a generic term that means 'many shapes'. the specialization relationship is implemented using the principle called inheritance. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones. which can be described as the “is-a” relationship. 4. Just like abstraction is closely related with generalization. as an example you can say that both IOException and SecurityException are of type Exception. while each concept is closely related with one another. Exception generalizes the shared characteristics of both IOException and SecurityException. nurses with milk. while understanding the way each related with other concepts. but to differ in those characteristics that are specialized in cats. 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. As such. The specialization and generalization relationships are both reciprocal and hierarchical. which is called the derived class or subclass. we mean that the dog is a specialized kind of mammal. and dogs and cats specialize mammals to their own specific subtypes. That mean the IOException is a specialized kind of Exception. In OOP. A cat is also a mammal. In other words. When we say that a dog is a mammal. This is the most common and most natural and widely accepted way of implement this relationship. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats. but it specializes these characteristics to the familiar characteristics of canis domesticus. Hence one has to be extremely careful to correctly understand each concept separately.public class IOException : Exception { } According to the above example the new class (IOException). inherits the members of an existing class (Exception).17. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity. operator overloading and method overriding. the inheritance is closely related with specialization.

Collapse Collapse public class Complex { private int real.18.Imaginary). int imaginary) { this. Collapse Collapse public class MyLogger { public void LogError(Exception e) { // Implementation goes here } public bool LogError(Exception e.4.Imaginary + c2.imaginary = imaginary. . while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.Real. } } 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. public int Real { get { return real.19. } public static Complex operator +(Complex c1.real = real. 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 +. } } public Complex(int real. Complex c2) { return new Complex(c1.or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments. public int Imaginary { get { return imaginary. c1. this. .Real + c2. } } private int imaginary. string message) { // Implementation goes here } } 4. What is Method Overloading? The method overloading is the ability to define several methods all with the same name.

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 superclasses.

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 twotier 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.

Three-tier is a client-server architecture in which the user interface. each technology (Java. . The 3-Tier architecture has the following three tiers. some time on separate platforms. In particular. 1. Presentation Tier or Web Server: User Interface. data storage and data access are developed and maintained as independent modules. stored procedures etc 4. functional process logic. Unfortunately. displaying/ accepting data/ input to/ from the user 2.NET version of MVC. seems to have originated within Rational Software. Application Logic/ Business Logic/ Transaction Tier or Application Server: Data validation. as well as the concept of multi-tier architectures (often refers to as three-tier architecture). and the actions based on user input into three separate classes. the presentation. The definitions given bellow are the closes possible ones I found for ASP. command.This architecture has aggressively customized and adopted by modern day system designer to web systems. ASP. acceptability check before being added to the database and all other business/ application specific operations 3. connection. What is MVC architecture? The Model-View-Controller (MVC) architecture separates the modeling of the domain. The term "three-tier" or "three-layer". Data Tier or Database server: Simple reading and writing method to database or any other storage.27. the term "controller" has been used to mean different things in different contexts. the popularity of this pattern has resulted in a number of faulty usages.NET etc) has defined it in their own way making it difficult to understand.

Some means of connecting services to each other is needed. Controllers: The handling of events or the controlling is usually done in the code-behind class. XML etc) are the most common use of the model. What is SOA? A service-oriented architecture is essentially a collection of services.Net technology introduces the SOA by mean of web services. 2. object collection.1. The . View: The ASPX and ASCX files generally handle the responsibilities of the view. 3. 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.28. Model: DataSet and typed DataSet (some times business object. 4. In a complex n-tier distributed system the MVC architecture place the vital role of organizing the presentation tier of the system. .

It has it's great share in the future of the IT world. hospital. The citizens are given a unique identifying card. and factory are equipped with a computer system where that system is connected to a central . According to the imaginary diagram above. station.The SOA can be used as the concept to connect multiple systems to provide services. Each service centers such as shopping complex. where that card carries all personal information of each citizen. we can see how the Service Oriented Architecture is being used to provide a set of centralized services to the citizens of a country.

It should not include complex application/ business logics. The business entities should meaningfully define considering various types of requirements and functioning of your system. The customer finished the shopping and then by the time he leaves the shopping complex.30. which is a key part of every n-tier system. They contain not only most part of the business logic. which run through several cases before doing a simple retrieval. which is responsible of providing service to a city. where the regional computer system will manage the process. What is the Data Access Layer? The data access layer (DAL). I have seen systems with lengthy. You can change as and when you feel comfortable that the method you apply is flexible enough to support the growth of your system. If SP is getting longer and complicated. In some other cases. It is a balance one needs to find with their experience. is mainly consist of a simple set of code that does basic interactions with the database or any other storage device. Update. it is not even been well thought out.29. 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). 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. but be careful when selecting them. These functionalities are often referred to as CRUD (Create. except taking from one and passing to the other. 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. 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 data access layer need to be generic. simple. As a general advice when you define business entities. and Delete). rather than define a separate business entity for each table of your database. 4. The system welcomes the customer. It is recommended to identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your application. he will be asked to go through a billing process. but from the other hand by reading many articles I have become aware that not everyone agrees to what business logic actually is. Retrieve. . complex store procedures (SP). but application logic and user interface logic as well. 4. There are many great ways. you must decide how to map the data in your tables to correctly defined business entities.server. However there are no god said things that cannot be changed in software world. if you want to combine data from couple of table to build a UI (User Interface) control (Web Control). they can over complicating the simple system. and in many cases it's just the bridge in between the presentation layer and the data access layer with having nothing much. What is the Business Logic Layer? I know for a fact that this is a question for most. quick and efficient as much as possible. then it is a good indication that you are burring your business logic inside the data access layer. For example. The payment will be automatically handled with the input details obtain from the customer identifying card.

Structural. once you get afraid at your early age. when you learn them for the first time. you will see a confusing similarity. In the image below. you will get afraid of design patterns too.31. But if you continue to study eventually.32. A way of passing a request between a chain of objects Command Encapsulate a command request as an object Interpreter A way to include language elements in a program Iterator Sequentially access the elements of a collection Mediator Defines simplified communication between classes Memento Capture and restore an object's internal state Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Strategy Encapsulates an algorithm inside a class Template Method Defer the exact steps of an algorithm to a subclass Visitor Defines a new operation to a class without change 4. They are categorized in three groups: Creational. If you observe the figure carefully. What is Gang of Four (GoF) Design Patterns? The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. So that it will make harder for you to understand them. it stays with you forever. It is like infant phobia. . Creational Patterns o o o o o Abstract Factory Creates an instance of several families of classes Builder Separates object construction from its representation Factory Method Creates an instance of several derived classes Prototype A fully initialized instance to be copied or cloned Singleton A class of which only a single instance can exist Structural Patterns o o o o o o o Adapter Match interfaces of different classes Bridge Separates an object’s interface from its implementation Composite A tree structure of simple and composite objects Decorator Add responsibilities to objects dynamically Facade A single class that represents an entire subsystem Flyweight A fine-grained instance used for efficient sharing Proxy An object representing another object Behavioral Patterns o o o o o o o o o o o Chain of Resp. and Behavioral. However. you will see an easily understandable color pattern (same color is used to mark the classes that are of similar kind). I am trying to compare the two one on one to identify the similarities. What is the difference between Abstract Factory and Builder design patterns? The two design patterns are fundamentally different.4. you have both design pattern listed in. So the result would be that you never look back at design patterns again. Here you will find information on these important patterns. Let me see whether I can solve this brain teaser for you.

Mark #4: Finally. both seem to produce some kind of a generic output.Please follow up with the numbers in the image when reading the listing below. • • • • 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 . Additionally both classes are of type abstract. Mark #1: Both patterns have used a generic class as the entry-class. It is “AbstractFactory” for one and “Builder” for the other. 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. while the other named it as “Director”. Mark #2: Here again the difference is the class name. Mark #3: Once again both patterns have defined two generic (WindowsFactory & ConcreteBuilder) classes. The only difference is the name of the class. Now. focusing on the differences. They both have created by inheriting their respective abstract class. One pattern has named it as “Client”. but this time.

maintainable and also very importantly expandable software systems. hence designing a system properly (this never mean an *over* desinging) is the key to the success. that it is realistic trying to make a programming language be everything to everybody. use it and review it if you have any questions/ criticisms around my design don't hesitate to shoot them here or there.com/useritems/System_Design. 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. The design or the architecture of a software system is the foundation. then this time it is not you.asp .. The language becomes bloated.aspx Practical Approach to Computer Systems Design and Architecture: http://www. so even though they look similar. they are not. 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. As an example builder can use one of the other patterns to implement which components get built or in another case Abstract Factory. 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. sustainable. When you talk about designing a software system. and Prototype can use Singleton in their implementations. after reading all these. Note: For newbies Rocket Framework is going to be little too advance but check it. 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. 5. Hope you all will enjoy reading it.com/en-us/library/default. 6.• • • • • • Abstract Factory: Focus on defining many different types of *factories* to build many *products*. In order to do it. What is the Conclusion? I don't think. What I Referred? • • MSDN Library: http://msdn2. that fully utilize the feature of the language to bring a competitively advance system to their customers. I hope that this shed some light to resolve the puzzle. If you still don’t understand it. the foundation of a system places a vital role. 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. and hard to read if everything plus the kitchen sink is thrown in. It hold the system together. it has to be me and it is since that I don’t know how to explain it.microsoft. hard to learn. In another word every language has their limitations. So the conclusion would be that the two design patterns exist to resolve two type of business problems. please check the source code of the latest of my open-source project name Rocket Framework. Builder. So for them to see these concepts being applied in real world systems. Finally.codeproject.

csharp-online.cmu.objectmentor.toa.com/Patterns/Patterns.net/Inheritance_and_Polymorphism %E2%80%94Specialization_and_Generalization Abstraction and Generalization: http://cs.html Service-oriented architecture (SOA) definition: http://www.html Basic Object-Oriented Concepts: http://www.• • • • • • • • • • Introduction: What is Object-Oriented Programming?: http://www.com Builder Design Pattern [Wiki] 7.Added more details to explain the Composition.kennesaw. as pointed here 26/01/2011 o Conclusion is updated and a link is added to Rocket-Framework License This article.ufsc.html Object Oriented Analysis and Design Team: http://atlas.com/web-services/articles/serviceoriented_architecture_soa_definition. 15/04/2008 o . History • • • • • 28/01/2008 o .aspx http://www.dofactory. is licensed under The Code Project Open License (CPOL) . o .edu/~aabyan/PLBook/HTML/AbsGen.Updated some of the wording slightly 31/05/2010 o .Added Comparison between Abstract Factory and Builder o . along with any associated source code and files.Added History section 04/02/2008 o .Corrected the 'Composition' related description.edu/~dbraun/csis4650/A&D/index.html http://www.servicearchitecture.inf.sei.br/poo/smalltalk/ibm/tutorial/oop.htm Inheritance and Polymorphism—Specialization and Generalization: http://en.edu/str/descriptions/clientserver.Added more content base on design principles.wwc.com/pub/oobasics/oobasics.htm Client/Server Software Architectures--An Overview: http://www.

not found in procedural programming languages. Better still. information hiding. 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. Simply put.NET Framework language can and should use the .NET Framework class library. don't they? OOP. and so is the first letter of any .NET as the language. providing a library is very easy. VisualBasic has evolved into VB. • • • Easy Maintenance.NET is declared using the keyword Class. Then. you can extend the functionality of the class library to provide classes that suit your needs. programmers of any . Code Reuse. let's look at some of the features of OOP. is also an OOP language. a fully OOP language.NET. etc. This means the first character of a class name is uppercase. such as easy code maintenance. 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. Classes Classes are the main focus in OOP. Listing 1: Class Employee Class Employee End Class As simple as that. There is a good reason for this transformation.Object Oriented Programming for VB. starting with the easiest one. polymorphism. but it is something to start with. Listing 1 presents a class called Employee. In fact. and code reuse. Having a class with certain functionality. using VB. you need to know the theory as well as do some OOP coding practice. Entities are represented by classes and classes with the same functionality are located in the same namespace (package). interface. you will probably hear him/her utter words such as class. Extensibility. a class is a data type that provides some functionality. It is not a complete reference. however. You can add a class into a namespace without affecting other members of the namespace. an extensive library that provides rich functionality. encapsulation. Those sound cool. classes. And Java. OOP Features Now. Modularity is inherent in OOP. you can quickly extend that class to create a different class with extended functionality. one of the most popular languages on the planet. Note that Microsoft recommends the use of Pascal-case naming for classes. of course.NET . OOP naturally supports extensibility. For example. inheritance.Part 1 by Budi Kurniawan 09/25/2001 If you ask an OOP guru what an OOP language is. This article offers readers just getting into OOP the very basics of OOP. A class in VB. Since functionality is encapsulated into a class and each class is an independent entity. extensibility. OOP offers several benefits. Some of the benefits are outlined below.

Class Members A class can have members such as fields. Examples of good field names are salary. just as the blueprint of a sports car is useless until assembly workers make the car. and so on. Creating an object is therefore known as instantiation. quarterlyBonus. properties and subroutines and functions. To use a class's field or method or any other member.subsequent concatenated words. In OOP. 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 . In other words. which means you capitalize the first character of each word except the initial character. Adding two fields called salary and yearlyBonus to the Employee class in Listing 2 will result in the following code. an object is said to be an instance of a class. A field name is camel-case. you need to first turn the class into an object. For example. Another type of class member is a field. The code in Listing 4 demonstrates the instantiation of the Employee class. you drive a car. not the blueprint of a car.Console. StringUtil. 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. Listing 2 presents the Employee class with a subroutine called Work. Good class names according to this convention include GeneralManager. SmallDictionary. Method names are also Pascal-case.Write(salary) End Sub End Class Instantiating an Object A class is a template or a blueprint of the entity that the class represents. 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. etc.

which is automatically installed when you install the . you can use its functionality. anEmployee = New Employee() Now that you have an object of type Employee. Pages: 1. anEmployee.Console.System. The Main sub first declares an object variable of type Employee.) In our example. which is the entry point of a VB.Write(salary) End Sub Next Page . we can call the PrintSalary method as follows. (Once the car is built.NET Framework. go to the directory where the file Employee. This approach is shown in Listing 5. If you are not using Visual Studio.Console.NET.vb is stored. The variable is called anEmployee. Dim anEmployee As Employee It then instantiates Employee with the keyword New. For instance.exe.vb. 3 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.Write(salary) End Sub End Class Module Module1 Public Sub Main() Dim anEmployee As Employee anEmployee = New Employee() anEmployee. you can start and drive it.NET program. You can also move the Main sub into the class. if you save your source code as Employee. 2. Now back to the code. you don't need a module. In order to compile. you can compile your VB. This way. a source file must provide access to the Main sub in one way or another.NET program with vbc. and then type vbc Employee.PrintSalary() End Sub End Module The module Module1 in Listing 4 provides the Main sub.PrintSalary() This will print the value of the salary variable in Employee.vb.

PrintSalary() End Sub End Class .Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee. you write classes and other types. For example.NET Framework class library in the . System. in the PrintSalary method in the Employee class we used the Console class in the System namespace. System.Drawing. Namespaces are discussed next.NET program. you can import a namespace so that you don't have to repeat it every time you want to use its member. For instance. To make your application more organized. This is also what Microsoft does with the . you can rewrite the code in Listings 4 and 5 as shown below.Write in the PrintSalary method means that you call the Write method of the Console class. Important namespaces you will frequently use include System. Namespaces When you write a .Forms. you can see there are more than 80 namespaces.IO. 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.PrintSalary() End Sub End Class Note that System. If you open the . If you will be using a namespace often.Windows. Console is part of the System namespace.NET Framework class library. you can group your classes into namespaces.NET Framework SDK documentation.Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee. etc. System.Console.

you have full control over what you want to expose. Use the keyword Friend to make a member have friend restriction. Access Types In many cases. Protected friend. Friend.. This means. Protected. These different access types provide for information hiding in OOP. when you write a class. This is the union of protected and friend. you can protect class members that you don't 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. Use the Protected keyword to make a member protected. A protected member is accessible to a derived class and from inside the class itself. For example. One of the great benefits of OOP is that you can restrict access to a class member. you can use the Console class in the PrintSalary method without mentioning the namespace because the namespace is already imported. they can call methods of that class or access its fields. VB. Pages: 1. Use the Private keyword to make a class member private. you will provide that class to other people so they can use its functionality. Private class member can only be accessed from inside the class itself. It can be called from anywhere. it is common practice to mention the namespace in front of the class name. the Console class in the System namespace is referred to as System. Members with the friend access restriction are accessible only within the program that contains the class declaration. You use the keyword Public in front of the class member to make it available publicly. To refer to a class correctly. For example. Namespaces also allow you to have classes with the same name in different namespaces.Now.Console.Console. In other words. the PrintSalary method in the Employee class is a public method. 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.NET offers levels of accessibility. i. as follows: • • • • • Public.e.PrintSalary() .Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee. Private. Public class members don't have access restrictions.

NET program. For instance.NET Framework SDK documentation.IO. 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. you can see there are more than 80 namespaces. Namespaces When you write a .NET Framework class library in the . you can import a namespace so that you don't have to repeat it every time you want to use its member. System. For example. System. System. you write classes and other types. Console is part of the System namespace. Access Types .End Sub End Class Note that System. in the PrintSalary method in the Employee class we used the Console class in the System namespace. If you open the .Windows. the Console class in the System namespace is referred to as System.Write(salary) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee.NET Framework class library. Namespaces also allow you to have classes with the same name in different namespaces. you can group your classes into namespaces. you can rewrite the code in Listings 4 and 5 as shown below. you can use the Console class in the PrintSalary method without mentioning the namespace because the namespace is already imported.Forms.Drawing. If you will be using a namespace often. etc. it is common practice to mention the namespace in front of the class name. Namespaces are discussed next.PrintSalary() End Sub End Class Now. To make your application more organized.Console.Write in the PrintSalary method means that you call the Write method of the Console class. To refer to a class correctly. This is also what Microsoft does with the . For example.Console. Important namespaces you will frequently use include System.

or you can have methods that are not accessible by anyone other than from inside the class itself. Static means the member is available without having to instantiate an object.NET. It can be called from anywhere. This is because in OOP languages there is a special type of member called a static member. the class called SalaryLevel provides static fields only in Listing 7. Listing 7: Static members in a class Class SalaryLevel Public Shared Level1 Public Shared Level2 Public Shared Level3 Public Shared Level4 Public Shared Level5 Public Shared Level6 Public Shared Level7 Public Shared Level8 As As As As As As As As Decimal Decimal Decimal Decimal Decimal Decimal Decimal Decimal = = = = = = = = 35000 40000 45000 50000 55000 60000 65000 70000 . you may wonder why we can use the Write method of the System. 2. the PrintSalary method in the Employee class is a public method. The term shared is also used in VB.Console object. For example.. they can call methods of that class or access its fields. You can write methods that can be called by other programmers. This is the union of protected and friend. Protected. Private class member can only be accessed from inside the class itself.In many cases.e. Friend. i. These different access types provide for information hiding in OOP.Console class without first instantiating a System. A protected member is accessible to a derived class and from inside the class itself. Members with the friend access restriction are accessible only within the program that contains the class declaration. Private.NET offers levels of accessibility. Protected friend. You use the keyword Public in front of the class member to make it available publicly. as follows: • • • • • Public. you have full control over what you want to expose. 3 Next Page Static Members Looking at the Employee class in Listings 4. 5 and 6 again. you can protect class members that you don't want to expose. Use the Protected keyword to make a member protected. In other words. Public class members don't have access restrictions. when you write a class. One of the great benefits of OOP is that you can restrict access to a class member. Pages: 1. Use the keyword Friend to make a member have friend restriction. Use the Private keyword to make a class member private. This means. VB. For example. you will provide that class to other people so they can use its functionality.

as you have seen. Members that are not static are called instance members.NET will create one for you. Constructors A constructor is a special method that must be present in a class for the class to get instantiated. If you write a constructor explicitly in your class. you can then write a new class that extends the original .Write(SalaryLevel. When there is no constructor present. VB. VB.NET won't create it anymore. Inheritance Inheritance is a feature that allows you to extend a class. That's right. But.NET. You can provide initialization code that is guaranteed to run when the object is instantiated. this method is called New. use the static field of SalaryLevel Console.Public Shared Level9 As Decimal = 75000 Public Shared Level10 As Decimal = 80000 End Class You can then use the class in your program. When you instantiate an object by using the New keyword. If part of the functionality you need has been provided in a class written by someone else. In VB.Level4) End Sub Public Shared Sub Main() Dim employee As Employee employee = New Employee() employee. we can use the Level4 static field in the SalaryLevel class without first creating an object of type SalaryLevel. there is no New method in the classes in the previous code. the class's constructor is called.PrintSalary() End Sub End Class In the PrintSalary method of the Employee class. 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. you can create a brand new class. If you need some functionality. as illustrated in Listing 8. however.

For example. IT PROBABLY BELONGS AS TEH FIRST LINE OF CODE. and the original class is called the parent class or the base class. you can instantiate a Manager object and use members from the Employee class. extending a class is done using a semicolon after the class name. Syntactically. Your class is called the child class or derived class. CHECK WITH AU. The code is given in Listing 10.NET a class can only extend one parent class. 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. The process of extending a class is called extension.Write(salary) End Sub End Class Class Manager: Inherits Employee . the term subclass or inherit is used to describe the act of extending a class. Class Manager Inherits Employee End Class Now.class. you don't need the semicolon. //////QUESTION: IMPORTS SYSTEM WAS STUCK IN THE ABOVE GRAF.Write(salary) End Sub End Class Class Manager: Inherits Employee End Class If the word Inherits appears on the next line. Listing 9 shows how we extend the class Employee to create a new class called Manager.NET.////////// 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. followed by the word Inherits and the parent class name. In VB. Multiple class inheritance is not allowed in VB. Sometimes.

NET Framework class library. For example. which itself is a child of Control.Windows.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. the Button class in the Windows.Object is called the root or the superclass in the . Why would you want to make your class non. System.Form End Class This blank class declaration.Form.NET Framework class library consist of hierarchies of classes that are derived from other classes.Forms namespace is a child class of ButtonBase. you can't make the yearlyBonus field private.Write(yearlyBonus) End Sub End Class Note that member accessibility restriction applies. Therefore. The power of inheritance can be demonstrated by the code in Listing 12. This is because MyForm inherits System. Inheritance is a common practice.Forms.End Class Module Module1 Public Sub Main() Dim manager As Manager manager = New Manager() manager. Listing 12: Extending System. You can create a form without a single line of code.inheritable? In some cases. In fact. since this field is not accessible from the Manager class. It inherits the functionality of the Form class. All classes will eventually have the System. For example. the . Listing 11: Adding a method to the derived class Class Manager: Inherits Employee Public Sub PrintBonus() Console. For example. Listing 13: A non-inheritable class NotInheritable Class Calculator End Class Trying to extend this class will raise a compile error.Object class as its root. trying to compile the code will result in an error. when compiled and run. NotInheritable Classes You can prevent classes from being inherited by using the NotInheritable keyword. the code in Listing 13 is a class called Calculator that cannot be inherited.WIndows.Windows. you may not want other people to be able to extend .Forms.Form Public Class MyForm : Inherits System.Forms. will display a Windows form.

your class. however. You should use inheritable classes with caution. Part 2 of this series can be found here . This type of class is also called a final class in some other OOP languages. because noninheritance defeats the purpose of OOP. Another reason is that an inheritable class produces faster code. Only use it if you are 100% sure that you will not extend the class.

vb source code file.Forms. You need Microsoft ."System. Inheritance and Polymorphism. 2.NET. To educate how Object Oriented techniques are used in VB.NET.vb /out:"filename. you may use the command prompt to type: vbc filename. o Overloading and Overriding. o Encapsulation. 3. To provide a sound knowledge about Object Oriented Programming in VB.NET code. Go through this tutorial and you will start making sense of almost any . This tutorial is designed with the following objectives: 1.NET framework SDK installed in your system to compile and execute the exercises in this article.NET.exe" /r:"System. To explain the following concepts in an easy and simple way: o Creating and using classes and objects in VB.NET compiler (vbc. Classes & Objects. o Constructors and Destructors. This article uncovers some basic Object Oriented Programming features of Visual Basic.Object Oriented Programming In VB.Windows.dll". Abstraction.NET Contents • • • • • • • • • • • • Introduction Using the code Lesson 1: Namespaces. The whole article is divided into ten lessons.exe) normally resides in your FrameworkSDK\bin folder. The source code for these lessons is provided with the article. Also. Modules A Namespace .NET is completely object oriented. NET.dll" 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. You can download it from the Microsoft website. Using the code The source code for each lesson is available as a . o Static functions. The VB. To manually compile a source code file.NET. Java/CPP programmers can use this to understand OOPs in VB.

Jimmy is an object of type Dog. by simply importing the namespace. you are already familiar with classes and objects. Collapse Collapse Imports System A Class Probably. grouped together to various namespaces. Human is a class for representing all human beings. Import the System namespace (already available in . You can use the classes in a namespace. a Class is a definition of a real life object. .In VB. Simply speaking. Dog is a class to represent all Dogs. Animals is a namespace. We will create an object in the next section.NET. 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.NET framework provides a rich set of built in classes. Modules . we are using the System namespace. The Imports keyword is used to import a namespace to your project. classes and other data structures for a specific purpose are grouped together to form a namespace.NET).Writeline ("Dog is barking") End Function End Class End Namespace An Object An object is an instance of a Class. In this lesson. For example. Classes can contain functions too. Read on. For example.

the class Dog is in the 'namespace Animals (see above). 'We use Animals. Functions and Subroutines are almost the same. See below End sub OurFunction() 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. Public functions in modules can be called directly from anywhere else.Bark() End Function End module . Collapse Collapse Public Module modMain Execution will start from the Main() subroutine: Collapse Collapse Sub Main() 'Call our function. VB provides Functions and Subroutines.Dog 'Create an object. Dim Jimmy as Animals. Unlike functions in classes. Unlike in VB 6. Jimmy = new Animals. it is not required to use 'the 'set' keyword.Dog() 'Another way to create an object is 'Dim Jimmy as new Dog 'Call Jimmy's Main Function Jimmy.Dog because.You can use modules to write common functions. A Module is a group of functions. but the difference is that a subroutine can't return a value.

A Class may contain functions. Friend and Protected. Import the System namespace (already available in .Writeline ("Dog is walking") End Function End Class End Namespace . Collapse Collapse Imports System Animals is a namespace. in Inheritance (Lesson 5). We will see this later. they can be accessed by creating objects of the Class.Lesson 2: Access Types The major access types are Public. but they have some special use while inheriting a Class.NET). It is Private.Writeline ("Dog is barking") End Function Walk is a function in this class. It is Public: Collapse Collapse Public Function Bark() Console. Private. Collapse Collapse Private Function Walk() Console. Private and Protected members can be accessed only by the functions inside the Class. Friend members can be accessed only by elements of the same project. and not by the ones outside the current project. variables etc.. which can be either Public or Private or Protected or Friend. Protected members are much like Private members. Collapse Collapse Public Class Dog 'A public variable Public AgeOfDog as Integer Bark is a function in this class. Collapse Collapse Namespace Animals Dog is a class in the namespace Animals. Let us expand our dog class. If they are Public.

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.Walk End Function End Module Additional Notes: Encapsulation Putting all the data and related functions in a Class is called Encapsulation. Uncomment this and try to compile. 'Jimmy. it will 'cause an error. variables used to hold data (like the age of a dog) is declared as Private. because 'Walk() is outside the class Dog 'So this is wrong.Our Module: Collapse Collapse Public Module modMain Execution will start from the Main() subroutine: Collapse Collapse Sub Main() 'Call our function. because Bark & Ageofdog are public Jimmy. Protecting the data of an object from outside functions is called Abstraction or Data Hiding.Bark Jimmy. in a Class. Data Hiding or Abstraction: Normally.Dog() 'This will work. This prevents accidental modification of data by functions outside the class. Functions or property routines are used to access these variables. See below OurFunction() End sub 'OurFunction: Called from Main() Function OurFunction() Dim Jimmy as Animals.Dog Jimmy=new Animals.AgeOfDog=10 'Calling the Walk function will not work here. The Shared modifier indicates that the method does not operate on .

Collapse Collapse Namespace Animals Dog is a class in the namespace Animals. .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 Public Function Walk() Console.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 Class Dog Bark is a now a Public. It is not shared.Writeline ("Dog is barking") End Function Walk is a Public function in this class. Collapse Collapse Imports System Animals is a namespace. shared function in this class. Collapse Collapse Public Shared Function Bark() Console.

Writeline ("Adding Integers: " + Convert.ToString is equivalent to the good old CStr. Try 'moving Main() from this module to the above class End sub End Module Lesson 4: Overloading Overloading is a simple technique. Collapse Collapse Imports System Class Adder Here. we have two Add() functions.Dog Jimmy=new Animals. This one adds two integers. Let us see a simple Adder class.ToString(a + b)) End Sub This one adds two strings. Collapse Collapse Overloads Public Sub Add(A as Integer.Dog() Jimmy. i. Collapse . Dim Jimmy as Animals. Animals. to enable a single function name to accept parameters of different type. Import the System namespace (already available in . we can write the Main() function itself as a shared 'function in a class. 'with out creating an object of type Dog 'because it is shared.Collapse Collapse Sub Main() 'We can call the Bark() function directly.Bark() 'We can call the Walk() function only 'after creating an object.e Shared Sub Main().NET). B as Integer) Console. Convert. because 'it is not shared.Walk() 'Now Guess? The WriteLine() function we used so far 'is a shared function in class Console :) 'Also.Dog.

You can use the Inherits keyword for this. we used the 'Overloads keyword. Shared Sub Main() Dim AdderObj as Adder 'Create the object AdderObj=new Adder 'This will invoke first function AdderObj. a derived class acquires the attributes of its base class. B as String) Console. In simple terms." how are you") End Sub End Class Lesson 5: Inheritance Inheritance is the property in which. to overload them. Collapse Collapse Imports System Our simple base class: Collapse Collapse Class Human 'This is something that all humans do Public Sub Walk() Console.NET). Collapse .Writeline ("Adding Strings: " + a + b) End Sub 'And both have the same name.Add("hello".Writeline ("Walking") End Sub End Class Now.Collapse Overloads Public Sub Add(A as String. let us derive a class from Human.Add(10. it should be a shared function. using an existing class (base class). Let us see a simple example. A Programmer is a Human. we have the Main Function with in this class. you can create or 'inherit' your own class (derived class). 'your main function inside the class. Import the System namespace (already available in . When you write.20) 'This will invoke second function AdderObj. 'Here. This is possible because.

you can define a new implementation of the method in the derived class.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. The Overridable keyword is used to mark a function as overridable. if you specify 'NotInheritable Class Human'. Lesson 6: Overriding By default.Writeline ("Stealing code") End Sub End Class Just a MainClass.e. • NotInheritable The NotInheritable keyword specifies that a class cannot be inherited.. a derived class Inherits methods from its base class. 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. I. Let us see an example. . The keyword Overrides is used to mark that a function is overriding some base class function.Walk() 'This is also correct because Tom is a programmer Tom.Collapse Class Programmer Inherits Human 'We already have the above Walk() function 'This is something that all programmers do .) Public Sub StealCode() Console. I.e. if you declare our Human class as "MustInherit Class Human".. then you can't create objects of type Human without inheriting it. no derived classes can be made from the Human class. that is. If an inherited property or method needs to behave differently in the derived class it can be overridden.

let us derive a class from Human: An Indian is a Human: Collapse Collapse Class Indian Inherits Human 'Let us make Indian speak Hindi.Import the System namespace (already available in . Collapse Collapse Class MainClass 'Our main function .Writeline ("Speaking Hindi") 'Important: As you expect. If you need to 'call Speak() in base class. 'Like this 'Mybase. you can use MyBase keyword. the National Language 'in India 'Speak() is overriding Speak() in its base class (Human) Overrides Public Sub Speak() Console.Speak() End Sub End Class Just a class to put our Main(). 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.NET). any call to Speak() inside this class 'will invoke the Speak() in this class.

For example. On the contrary. Then. an object of Human type can be used to hold an object of any of its derived type. The only difference is in the Shared Sub Main() in the class MainClass. Collapse Collapse Imports System This example is exactly the same as the one we saw in the previous lesson. You derived a child class from your base class and overloaded the function speak(). let us assume that you have a function named speak() in your base class. if you have a base class named Human.Speak() 'This call will invoke the Speak() function 'in class Indian Tony. you create a child class object and assign it to a base class variable. Now. See the example. So scroll down and see an example: Our simple base class: Collapse Collapse Class Human 'Speak() is declared Overridable Overridable Public Sub Speak() . then the speak() function in the base class will work. the system will automatically determine the type of the object to call the appropriate function.Speak() End Sub End Class Lesson 7: Polymorphism Polymorphism is the property in which a single object can take more than one form. When you call a function in your object. Import the System namespace (already available in . if you are assigning an object of the base class to the base class variable. if you call the speak() function using the base class variable. This is achieved through runtime type identification of objects. the speak() function defined in your child class will work.NET). For example.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.

because 'Indian IS_A human. .Writeline ("Speaking Hindi") 'Important: As you expect.Writeline ("Speaking") End Sub End Class Now. 'Now. Collapse Collapse Class Indian Inherits Human 'Let us make Indian speak Hindi. you can use MyBase keyword. If you need to 'call Speak() in base class. let us derive a class from Human.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. 'Like this 'Mybase. let me call Speak as Tom.Speak() 'Which Speak() will work? The Speak() in Indian. An Indian is a Human. I am assiging an Indian (derived class) Tom=new Indian 'The above assignment is legal. Tom is declared as a Human. or the 'Speak() in human? 'The question arises because.Console. the National Language 'in India 'Speak() is overriding Speak() in its base class (Human) Overrides Public Sub Speak() Console. any call to Speak() inside this class 'will invoke the Speak() in this class.

the Speak() in Indian will work. but unlike the functions. Constructors can be overloaded (see Lesson 4).'but an object of type Indian is assigned to Tom. Collapse Collapse Imports System A Constructor is a special function which is called automatically when a class is created.NET). Dog is a class: Collapse Collapse Class Dog 'The age variable Private Age as integer The default constructor: Collapse Collapse Public Sub New() Console. This is because.NET. 'The Answer is. you should use useFinalize() routine to create Destructors. In VB. the Overloads keyword is not required.NET. 'This is called Polymorphism End Sub End Class Lesson 8: Constructors & Destructors Import the System namespace (already available in .0.net can automatically 'detect the type of the object assigned to a base class variable.Writeline ("Dog is Created With Age Zero") Age=0 End Sub The parameterized constructor: Collapse Collapse . In VB. you should use useNew() to create constructors. A Destructor is a special function which is called automatically when a class is destroyed. 'most object oriented languages like Vb. They are similar to Class_Initialize and Class_Terminate in VB 6.

Writeline ("Dog is Destroyed") End Sub 'The Main Function Shared Sub Main() Dim Jimmy.Public Sub New(val as Integer) Console. Import the System namespace (already available in . Collapse Collapse Imports System Dog is a class. You can use the Get/Set keywords for getting/setting properties. 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. See the following example.Writeline ("Dog is Created With Age " + Convert. Collapse Collapse Public Class Dog 'A private variable to hold the value Private mAgeOfDog as Integer This is our property routine: . when 'the program ends. This is done by the Garbage 'Collector.NET). properties use property procedures to control how values are set or returned.ToString(val)) Age=val End Sub This is the destructor: Collapse Collapse Overrides Protected Sub Finalize() Console. 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.

Form .Drawing are inheriting a class named SimpleForm. The Age Set routine will work Jimmy.Writeline ("Setting Property") mAgeOfDog=Value End Set End Property End Class Another class: Collapse Collapse Class MainClass 'Our main function.Age() End Sub End Class Lesson 10: A simple program Let us analyze a simple program. The Age GEt routine will work Dim curAge=Jimmy. 'Set it.Forms System. so we should 'use Age() property routine. Execution starts here.Writeline ("Getting Property") Return mAgeOfdog End Get Set(ByVal Value As Integer) 'Called when someone tries to assign a value Console.Collapse Collapse Public Property Age() As Integer 'Called when someone tries to retreive the value Get Console. Dim Jimmy as Dog Jimmy=new Dog 'We can't access mAgeofDog directly. First. let us import the required namespaces: Collapse Collapse Imports Imports Imports Imports 'We System System.Forms.ComponentModel System. Shared Sub Main() 'Let us create an object.Age=30 'Get it back.Windows. from the 'class System.Windows.

Forms. and probably implement more OOP features in your VB. Public Class SimpleForm Inherits System.Forms.Text = "Hello.Run(sf) End Sub End Class That is it. in my next article.NET.Form 'Our constructor Public Sub New() 'This will invoke the constructor of the base 'class MyBase. We inherited this property from the base class: Collapse Collapse Me.New() Set the text property of this class.' 'i.Application. Now you can atleast read and understand most of those VB.NET source code. I'll try to cover the patterns and practices in VB. Now.e.Windows.NET programs.Windows. Windows is a namespace in system. 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. and Form is a class in Forms. Forms is a 'namespace in Windows. .

Interfaces provide a template for classes. such as an Eat method. your code would simply call the appropriate method (ie Eat). an IAnimal interface (the I standing for Interface) would have Eat. ie a Dog. Sleep. Using polymorphism. Therefore. with Polymorphism. you would have to create different variables depending on what animal was selected. you could use different classes. Instead. it would have an Eat method. but they would go about this in very different ways. . Then. both a Dog class and a Mosquito class would have a Eat method. the user can select what animal he/she wants. Rest and Go methods. All of these classes would implement an IAnimal interface.Polymorphism and Interfaces Polymorphism is the idea that many classes can provide the same property or method. the class is still allowed to have its own properties and methods too! *** We'll see how to use Polymorphism in the next section. say cDog. any class that uses this Interface. For example. Cat. you do not need to worry whether the class is a Dog or a Mosquito. however. eat. Rest and Go methods. Imagine you have a variable called 'Animal'. Sheep or Mosquito. For example. Dog = Bark at owner. This can be very useful when programming.. without having to worry what type of class it is. Sleep. you know that both these classes will have methods that are used in both. When your program starts. Calling this method. would involve different actions depending on the type of animal. Visual Basic allows you to do this through Interfaces. depending on the animal. sleep etc. must also have Eat.. which then means that when the user clicks on a command. however. and a Sleep method. and know that no matter what type of animal it was. and have different procedures that needed to be called when the user clicks on a command. the user can control the animal by pressing buttons telling it to move forward. which forces any classes that use the Interface to have the same properties and methods as the Interface. Sheep = Bend over head and eat grass and Mosquito = Find human! *** Don't forget. However. cCat etc. that even if you reference a template. Without Polymorphism.

b As Integer) As Integer Add = a + b End Function Overloads Public Function Add(a As Double. of course. For example. The use of the Overloads keyword is optional. however.Object Oriented Programming for VB.WriteLine(counter.WriteLine(counter. VB7 and also known as VB. For example. Both functions and subroutines can accept arguments.Add(1.NET. as long as those methods have different lists of arguments.3. You also might want to check out part one of this series. 5. which shows the class Calculator with two Add methods. But you really want to call both methods Print. is that a function in Visual Basic returns a value. you add the keyword Overloads as the first part in the method signature. Here is an article for VB programmers who want to learn OOP and have a quick grasp of it. as well as a method that prints a string.Add(1. OOP languages.Part 2 The new version of Visual Basic. you may need a method that prints a double. The first overload accepts two integers and the second overload accepts two doubles. Imports System Class Calculator Overloads Public Function Add(a As Integer. consider Listing 14. allow multiple methods to have the same name. of course.NET. 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. This is called method overloading. Method Overloading A method is either a subroutine or a function.NET. while a subroutine does not. writing code in an OOP way probably is. But there are situations where you need methods that do similar things but accept different lists of arguments. What do you do? You can write two methods and call them PrintDouble and PrintString respectively. use a name that reflects what the method does. When choosing method names. Even though the concept of objects is not entirely new to VB programmers. you should. In VB.9)) . offers the full features of an OOP language.NET . 5)) ' pass two doubles Console. including VB. because that is what they do. The difference. Each of the methods with the same name is comfortably called an overload. you can still have methods with the same name without using the keyword.

b As Double) As Decimal' and 'Public Overloads Function Add(a As Integer. we instantiate a Calculator object and call the Add method twice. On the first call to the Add method.WriteLine(counter. ' pass two integers Console. For instance. Two methods with the same name that accept the same list of arguments will not compile.End Sub End Module In the Main sub in the Module1 module. In order to be an overload. b As Double) As Double Add = a + b End Function End Class When you compile the class. we pass two doubles. it will report the following compile error: error BC30301: 'Public Overloads Function Add(a As Integer.9.WriteLine(counter. Take the Console class in the System namespace as an example. Method overloading can also be found almost everywhere in the . The first call to the Add method returns 6.3 and 5.9)) The smart thing is.NET Framework Class Library. one that accepts an integer. They cannot overload each other. This is not the case. Listing 15: Incorrect method overloading Imports System Class Calculator Overloads Public Function Add(a As Integer. The Write method has 18 overloads. the Common Language Runtime knows which method overload to call.Add(1. and so on. we pass two integers. 5.Add(1. These overloads make sure that you can pass any type of data to the Write method and the method will still work correctly. the second method returns 7.2. even though the types of their return values are different. the method must accept a unique set of arguments.3. even though they return different return types. b As Double) As Decimal Add = a + b End Function Overloads Public Function Add(a As Integer. 5)) On the second call. b As Double) As Double' differ only by return type. . Beginners to OOP often make the mistake of thinking that methods can be overloads if the return values are of different types. This class has a method named Write that outputs the representation of a value to the console. the Calculator class in Listing 15 will not compile because the two Add methods have the same set of arguments. 1 and 5. ' pass two doubles Console. 1. There is one overload that accepts a Boolean.

") End Sub End Class You can make a method not overridable by using the keyword NotOverridable. This technique is called method overriding. The method is declared overridable. . Pages: 1.Add(1. For example.NET you can do this by using the keyword Overridable in front of the declaration of the method in the base class. Listing 16 shows a class called Employee with a method called Work. In the Manager class. meaning that the method can be overridden in the inheriting classes. 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. the Work method in the Employee class in Listing 18 cannot be overridden. Then. 2. Listing 17: Method overriding Class Manager: Inherits Employee Overrides Public Sub Work() Console. Listing 16: An overridable method Imports System Class Employee Overridable Public Sub Work() Console.Why doesn't the compiler allow that? Because a function can be called without expecting a return value.") End Sub End Class The code in Listing 17 is a class called Manager that extends the class Employee in Listing 16. we provide a different implementation for the method Work. in the derived class.Write("I am a manager.89) it would not be clear which overload is being called. you use the keyword Overrides in front of the method with the same name. 5. For example. in the case of the erroneous Calculator class. For example.Write("I am an employee. In VB. 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.

the class looks like a normal class. Listing 20: Inheriting from an abstract class Class Rectangle: Inherits Shape Overrides Sub Draw() ' Draw a rectangle here End Sub End Class . When you extend an abstract class. An abstract method is denoted by the MustOverride keyword. you must provide implementations for all methods that must be overridden. the class in Listing 19 is named Shape and it is abstract because one of the methods (Draw) does not have implementation. Otherwise. Implementation can only be provided by the inheriting class. Other than that.") End Sub End Class Abstract Classes In some cases. so why bother providing an implementation at all? If this is the case. The class itself has the MustInherit modifier because it cannot be instantiated using the New keyword. For example.Listing 18: Not overridable method Imports System Class Employee NotOverridable Public Sub Work() Console. Or. the inheriting class itself will be an abstract class and must be declared with the MustInherit keyword. your class is incomplete. The method that you don't provide implementation for is called an abstract method. 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. this is called an abstract class.Write("I am an employee. The Rectangle and Line classes in Listing 20 inherit Shape. you don't know how to write the implementation of a method in a class at the time of writing the class. you know that the method will be overridden in the child classes.

there is a naming convention for interfaces. Like other types in VB. etc. IPolygonShape. you must make your class abstract.NET. the same syntax as class extension is used. you use the keyword Implements. inheritance plays a very important role. An interface is declared using the keyword Interface. Listing 21 presents an interface called IShape. 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 is like an abstract class. here are some good names for interfaces: IScalable. For example.NET. The recommendation is to use the class's naming convention and prefix the interface name with an I. the class Line implements the IShape interface. however. an interface can only have methods that don't have implementation. As with extending an abstract class. An abstract class can have methods with or without implementations.NET class can extend multiple interfaces.NET. In the code in Listing 22. Extending an interface has a special term: implement. Listing 21: An interface called IShape Interface IShape End Interface For a class to implement an interface. To implement an interface in VB. I3DShape. ISerializable. you must provide implementations for all methods in the interface you implement.NET because a VB. interfaces are probably not very clear. In an OOP language that supports only single class inheritance like VB. Interfaces enable multiple inheritance in VB. Otherwise.Class Line: Inherits Shape Overrides Sub Draw() ' Draw a line here End Sub End Class Interfaces For beginners. Why would you want to use an interface at all? An interface defines a contract that classes must adhere to. For example.

There is also a class named Line that implements IShape.Write("Draw a line") End Sub End Class You can then instantiate a Line object as you would a normal class. if you type in the word polymorphism as a search keyword in an Internet search engine. properties and events. The same object or function can be used uniformly as a parameter in different type contexts without changes. which are . This type of polymorphism allows an object to belong to a number of classes. followed by the name of the interface and the method name. Listing 23: Implementing an interface method Imports System Interface IShape Sub Draw() End Interface Class Line Implements IShape Sub Draw() Implements IShape. and then performs the same kind of work irrespective of the parameter type. For example. polymorphism (literally means "many forms") is probably the most misunderstood term in OOP because the word has more than one meaning. you will find out that this word is also used in biology. interfaces cannot be instantiated. 2. In modern software engineering discipline.Draw Console. Inclusion polymorphism is what we know as subtyping and inheritance. Like abstract classes. the code in Listing 23 shows an interface called IShape with one method called Draw. For example. each method implementation must specify the interface method that it implements using the keyword Implements. 3 Next Page Polymorphism Polymorphism is probably the hardest concept to digest for those new to OOP. In the class that implements an interface. These polysyllabic forms of polymorphism are explained below. Universal polymorphism is considered purer than ad-hoc polymorphism and is also called "true polymorphism." Ad-hoc polymorphism is often described as "apparent polymorphism. • • Parametric polymorphism is the purest form of polymorphism*. Pages: 1. An interface cannot contain a field. polymorphism is classified into universal polymorphism and ad-hoc polymorphism.NET can only have methods. Indeed. The interface name and the method name are separated using a period.An interface in VB." Universal polymorphism is subdivided into parametric polymorphism and inclusion polymorphism. and ad-hoc polymorphism can be subdivided into overloading and coercion. 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. All interface members are implicitly public and may not specify an access modifier.

In other words. in OOP it is simply referred to as method overloading. Coercion allows a parameter to a function to be converted to the type expected by that function to avoid a type error. identified only two types of polymorphism: parametric polymorphism and ad-hoc polymorphism. This classification was put forward by Luca Cardelli (AT&T Bell Laboratories) and Peter Wegner (Brown University) in their paper. however. The older definition. the term is used to describe reference variables that may at run-time refer to objects of different classes. a class can be included in another class to create an inheritance hierarchy. yet still perform different functions.• • sometimes overlapping. if you have an object reference a whose type is A. or A must be an interface that is implemented by B or the class that B extends directly or indirectly. Data Abstraction and Polymorphism" (PDF).. In essence. Overloading is what is known as method overloading in object-oriented programming languages. Listing 24: An example of polymorphism Class Employee Public Overridable Sub Work System. It allows multiple functions to have the same name. This is the presently accepted definition of polymorphism.) In other words." To be more specific.Console.WriteLine("Managing . In OOP.Console.Work End Sub End Module .") End Sub Public Overrides Sub Work System. Consider the example in Listing 24. when we talk about polymorphism. Strachey in 1967." ) End Sub End Class Class Manager : Inherits Employee Public Sub Manage System. it is legal to assign and object of type B. it simply means "one interface.Console. (Overloading is also a type of polymorphism. published in Computing Surveys in 1985.WriteLine( "I am a manager" ) End Sub End Class Module ModMain Sub Main() Dim employee As Employee employee = New Manager employee.WriteLine( "I am an employee. Dim a As A a = New B() However. first put forth by C. "On Understanding Types. 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.. as in the following. many implementations. B must be derived from A either directly or indirectly.

when the Work method is called. By declaring control as Control.Control. guess what is written on the console? I am a manager. _ ByVal color As system.BackColor = color End Sub You pass two arguments to the ChangeColor sub: a System.The example has two classes: Employee and Manager. 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.Blue) Next Summary .Drawing. employee is assigned an object of type Manager. etc The code in Listing 26 iterates all controls in a Windows form and passes each control to the ChangeColor sub.Forms. Employee has a method called Sub and Manager extends the class Employee and adds a new method called Manage.Windows.Windows.Drawing. polymorphism allows you to pass a Control object or any object whose class is derived from the Control class. Color. 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. you write the subroutine in Listing 25.Color) control. Listing 25: The ChangeColor subroutine Private Sub ChangeColor(_ ByVal control As System. Listing 26: Passing different controls to the ChangeColor subroutine Dim control As System. You would have ChangeButtonColor.Forms. as in employee = New Manager Then. a Label or any control that may be used in a form. For this purpose.Forms. you only need one sub for all controls. You know that the Control class is the parent class of all Windows controls. This way. Without polymorphism. Running this code will give all controls in the current window a blue background color. The Main sub in the module defines an object variable called employee of type Employee.Control For Each control In Me. you need a sub for each type of control.Color object. Dim employee As Employee However. You want to be able to pass a Button. ChangeLabelColor. This means that it is the Work method of Manager class that gets called.Windows.Control object and a System.Controls ChangeColor(control.

you should have a much better understanding of all those cool words I presented at the beginning of the article.By now. you can start to take advantage of VB. With this understanding.NET's complete support for object-orienting programming. Happy OOPing! .

Surprisingly. considered the Nobel prize of computer science. however. The language is called Simula 67. You may find it hard to believe that a full-fledged OO language was implemented before structured programming and when. let's discuss why OOP in VB is a good thing. need more time and guidance in taking on this new challenge and opportunity. Others. It is true that VB6 supported some notion of objects. In this VB. in 2001 "for ideas fundamental to the emergence of object-oriented programming. it was considered too radical for practical use. we look at why VB6 programmers often find it hard to shift to OOP when the OOP itself is not difficult." Why OOP? OK. the language was reconstructed and given a new name: VB. barricades had not yet sprung up in the streets of Paris.NET offers its users. Some former VB6 developers have prepared themselves well to embrace this new version of the language. Ole-Johan Dhal and Kristen Nygaard from the University of Oslo and the Norwegian Computing Center (Norsk Regnesentral). Budi answers what is probably the most often asked question by newcomers to OOP: Why OOP? Finally. VB only became a fully OOP officially in 2002 and the inventors of this technology. Microsoft launched the .NET Framework languages and in order for VB programmers to be able to use the . only got their Turing Award. because at the time of invention.NET. this is not the case. Below. With the change to the language. For Microsoft. if VB is to become one of the .Introduction to OOP in VB." Its authors.NET by Budi Kurniawan 09/23/2002 Visual Basic . There are many benefits of OOP that make the technology so popular and the computing science society grateful to its inventors. With the introduction of the Framework. Discussions focus more on OO concepts rather than OO techniques. through their design of the programming languages Simula I and Simula 67. but lack of support for inheritance made it unfit to be called an OOP language. It's now a language that fully supports objectoriented programming. many VB fans might think that OOP is a natural progression from procedural programming. OO concepts were first introduced in 1966 in a journal paper titled "SIMULA-An Algol-based Simulation Language. in no particular order.NET Framework early this year and overhauled its most popular language: Visual Basic. OO technology did not become popular until the early 1980s. Modularity is Inherent in OOP . a mini-skirt could still cause a stir. short for simulation language. enough history. Object Oriented Software Construction. changing VB is more of a necessity than a choice. Ole-Johan Dhal and Kristen Nygaard. and that OO technology is a new technology. Budi Kurniawan introduces many facets of object-oriented design and programming to VB programmers new to OOP. as OO expert Bertrand Meyer puts it in his book. I will mention the three most important ones. later completed the first OOP language in the world." However.NET Framework Class Library.NET OOP series. among many other things. In the first article of this series. Now. a fully object-oriented programming (OOP) experience. "The Vietnam War was still a page 4 item.

anyhow. 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 also easy to write and distribute your own library. When you change something in some part of the program. 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." new errors will emerge as fast as you fix the old ones. I will also discuss the use of these patterns. However. which is a template for objects. which means the degree of interaction between two classes (modules). For instance. then.NET Framework comes with good documentation. you'll make it work. once said something like this: a small program can be written in anything. and to make it easier to refer to each solution. If you don't quit easily. you may not realize how the change might affect other parts. . the language shares the . Reusability does not only apply to the coding phase through the reuse of classes and other types.NET. Extendibility means that you can still use those classes by extending them so that they provide what you want. even those consisting of one million lines are not considered that large. 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. because it shortens the time taken to develop an application. that an OOP language often comes with a set of ready-to-use libraries. though. Once upon a time.Drawing namespace contains the collection of types used for drawing. when designing an application in an OO system. You still save time. Now.NET Framework Class Library with other . the System.Modern software applications tend to become larger and larger. if you need to make sure that a class can only have one instance. there is already a solution to it. In terms of reusability. at the end. because the . In future articles. you will probably find one or two that provide part of the functionality. is a module by itself. Bjarne Stroustrup. If you don't use techniques of "good programming. solutions to OO design problems can also be reused. These classes have been carefully designed and tested. with proper indexing and structured and searchable content. 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 . When a system gets larger. For example. because you don't have to write code from scratch. Modularity is inherent in OOP because a class. An important and related term that is used often in OOP is coupling. the pattern is given a name. Support for reusability in a programming platform is very attractive. The reason for this is there is interdependency among different parts of a large program. A good design should allow a class to contain similar functionality and related data. OOP Supports Extendibility Every application is unique. It is not surprising. Modularity makes maintenance less of a headache.NET Framework Class library. classes and other types are grouped into namespaces. a "large" system comprised a few thousand lines of code. In the case of VB. VB. It has its own requirements and specifications.NET languages. These solutions are called design patterns.NET programmers are lucky. What is the problem for those new to OOP is how to determine what methods and data should make up a class. it starts giving its developers problems. But a large program is a different story. This is another topic of its own. the father of C++. sometimes you cannot find an existing class that provides the exact functionality that your application requires.

These classes need the BackColor property as part of their user interface. Second Edition). explained in one of his papers why learning OOP seems harder than learning structured programming. however. Someone with procedural programming skill thinks in a paradigm very different from how OO programmers view and try to solve problems. VB6 Programmers and OOP Now. VB programmers need to master OOP. More recent studies. extendibility is achieved through inheritance.Form class.Form.In OOP.NET. Because your application has specific requirements that do not necessarily exist in other applications' specifications. Other classes that extend it get this property for free. which are basically objects. that makes it such a difficult task. He and other experts argue that it is how OOP is taught.NET Framework class library didn't put this method in the Control class. If you know the basic functionality that will be used in many cases. Researchers have been arguing about the best way to teach OOP at school. In many curricula. Monash University.Forms namespace. Michael Kolling. however. disqualify previous versions of VB from being an OOP language (for the criteria of an OO system. It is true that you could use and write COM components. .Windows. your class. etc. take a look at the Control class in the System. but in the MonthCalendar class. you can provide a generic class that can be extended later to provide functionality specific to an application. however. This is bad news for those wanting to learn VB. too. For instance. but you don't want your class to provide very specific functions.Windows. A good example is the System.NET Framework. You can extend an existing class. only MonthCalendar does. the designer of the .NET. To create a form in a Windows application. or change the behavior of methods you don't like. which provides basic methods. It is probably more appropriate to categorize the old VB into something between a procedural language and an OOP language. Therefore. are not fully OOP languages. Australia. If you create your own custom control by extending the Control class. When this person needs to learn OOP. The lack of other OOP features such as inheritance. In the light of this. The bad news is. properties. ScrollBar. MonthCalendar. I hope you agree with me that to work within the . As another example. from the School of Computer Science and Computer Engineering. add some methods or data to it. this is probably the reason that some people insist that VB6 is an OOP language. not OOP itself.Windows. it has the BackColor property that will be needed by all Windows controls. and events for a Windows form. we see that the OOP course can be taken when a student is nearing the final year of his/her university term. Examples of classes that extend the Control class are Label. have revealed the contrary. This class provides basic functionality for a Windows control.Forms. the VB versions prior to VB . You save time and programming (and debugging) efforts because you get the basic functionality of a form for free by extending System. will get the BackColor property for free. there is bad news and good news. you extend this class. including VBScript and Visual Basic for Applications (VBA). you can add the methods and data specific to your need.Forms. some argue that it is best to teach procedural programming before OOP is introduced. see Chapter 2 of Bertrand Meyer's Object-Oriented Software Construction. Not every control needs the SetCalendarDimensions method.

he/she has to go through a paradigm shift. VB. . though: OOP is not everything. Conclusion This article has presented the main benefits of OOP and why procedural programmers find it hard to learn OOP. Now the good news. It is said that it takes six to 18 months to switch your mindset from procedural to object-oriented paradigms.NET is a relatively easy language to program with.NET programmers do not need to worry about pointers.NET is easy. The . Once you know the nuts and bolts of OOP. For example. OOP is great for writing many types of applications. don't have to spend precious time solving memory leaks caused by forgetting to destroy unused objects.NET Framework also comes with a very comprehensive class library with relatively very few bugs in its early version. programming with VB. A word of caution. Another study shows that students who have not learned procedural programming do not find OOP that difficult. VB. some people cannot be convinced that using OOP is better at solving engineering or quantum mechanics problems than procedural programming. etc.

constructors are used for the sole purpose of creating an instance of a class. Protected. However. Therefore. yet you still can construct an Employee object.Work() There is nothing in the Employee class definition other than the Work method.") 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. Private. what they are used for. the class needs a constructor. A class can have multiple constructors.VB. If none is found. and some examples on using them. the previous Employee class is equivalent to the one below: Public Class Employee Public Sub New() End Sub Public Sub Work() System. it automatically adds a no-argument constructor.WriteLine("I am working. Understanding constructors well helps you write better classes. It therefore does not have a return value. What actually happens is the VB compiler checks for the presence of a constructor in a class it compiles. At a glance.NET OOP Part 2 .NET often don't pay enough attention to constructors. a constructor looks just like a method. the constructor in VB.Console. which is simply not true. or default). as given below: Public Class Employee Public Sub Work() System. This seems to contradict the previous statement that you need a constructor to instantiate an object of a class.WriteLine("I am working. What's worse is that many think constructors are just another type of method. For an object to be created from a class. Here are the characteristics of a constructor: • • • • • Always defined as a Sub. This article focuses on constructors.Understanding Constructors Beginners of OOP with VB. Say you write a class called Employee. In most cases. Can have any access modifier (Public.NET is called New. Friend.") End Sub End Class you cannot construct an Employee object using the following code: .Console. a constructor has a Public access modifier. The reason for this is their classes are usable even without a constructor. Regardless the name of the class.

"The Singleton Design Pattern. a constructor can also have a Protected. consider the Employee class and the Manager class that extends Employee. Singletons will be discussed in the next article. For example. the Employee class' no-argument constructor is also called. Note that the code in the base class' constructor is run before the code in the child class' constructor. For example.Console.") End Sub End Class Public Class Manager : Inherits Employee Public Sub New() System. constructors must be declared as a Sub and in most cases they have a Public access modifier.Dim employee As Employee employee = New Employee() This is because there is now no no-argument constructor in the Employee class. Friend. as in the following code: Public Class Employee Public Sub New() System. For example. like in the following code.WriteLine("Employee's constructor. the class won't compile.WriteLine("Manager's constructor. Public Class Employee Public Sub New(ByVal name As String) . However. If the base class does not have a no-argument constructor. or the default modifier.WriteLine("I am working. you use the Protected or Private modifier in a Singleton class to prevent the user from directly instantiating an object of that class. The call will be invoked from the first statement of the child class' constructor. Private.") End Sub End Class When the Manager class' constructor is invoked. the following code will produce a compile error because the Employee class (base class) does not have a no-argument constructor. In VB.") End Sub Public Sub Work() System. Dim manager As Manager manager = New Manager() The result on the console is as follows: Employee's constructor.Console.Console. the compiler will make a call from the child class' constructor to the base class' no-argument constructor." The Relationship With the Base Class If a child class extends a base class. Manager's constructor.

") End Sub Public Sub Work() System. 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.Console.") End Sub End Class Constructor calls are only valid as the first statement in a constructor.") End Sub End Class Thus.WriteLine("I am working. if you don't want to do this.Console.") End Sub End Class Public Class Manager : Inherits Employee Public Sub New(ByVal name As String) MyBase.New() in the Manager class' constructor calls the System. the constructor in the Manager class below is valid: Public Class Manager Public Sub New(ByVal name As String) MyBase.Object class if no class is explicitly defined as the base class.WriteLine("I am working.Console. Pages: 1.Console.New() System. you can use the MyBase keyword to reference any constructor in the base class.Console.Object class' noargument constructor.") End Sub Public Sub Work() System.") 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. the compiler does not add another call to the base class' no-argument constructor.New(name) System.Console.") End Sub End Class Public Class Manager : Inherits Employee Public Sub New() System.WriteLine("Employee's constructor.WriteLine("Manager's constructor. The MyBase statement must be the first line in the constructor: Public Class Employee Public Sub New(ByVal name As String) System.WriteLine("Manager's constructor. One solution to this problem is to add a no-argument constructor to the base class. However. Therefore.Console. 2 Next Page . Note that since MyBase is present in the child class' constructor. MyBase.System.WriteLine( _ "Employee's constructor with one argument.WriteLine("Manager's constructor.

Finally. Then it will initialize the id private field with the value 88.") End Sub End Class Here the nameField variable is initialized in the constructor. here is how you pass "Kevin" to the Manager object: Dim manager As Manager manager = New Manager("Kevin") . as in: System.") A constructor gives the user of your class a chance to pass a value for the initialization. The user of the class can pass a value for the nameField.WriteLine("Manager's constructor. Executes the rest of the class' constructor.") End Sub End Class First.Console.New(name) will be called.New(name) System. consider the following code: Public Class Manager : Inherits Employee Private nameField As String Public Sub New(ByVal name As String) nameField = name System.WriteLine("Manager's constructor. Initializes class-level variables. the compiler does some initialization in the following order: • • • Calls the base class' constructor.WriteLine("Manager's constructor.Initialization With Constructors One of the main uses of constructors is for data initialization.Console. When you create an instance of a class using the New keyword. For example. here is the code to pass "John" for the nameField variable: Dim manager As Manager manager = New Manager("John") And. For instance. consider the Manager class below : Public Class Manager : Inherits Employee Private id As Integer = 88 Public Sub New(ByVal name As String) MyBase. the compiler calls the WriteLine method.Console. MyBase. As an example.

") End Sub Public Sub New(ByVal name As String) nameField = name System. and uses the Me keyword to access the class-level variable. the following Manager class' constructor has an argument with the same name as a class-level variable.Console. Public Class Manager : Inherits Employee Private name As String Public Sub New(ByVal name As String) Me.WriteLine("Manager's constructor. the second constructor can be used. To access the class-level variable from inside the constructor. the user can use either constructor. Otherwise.") End Sub End Class Multiple Constructors A class can have multiple constructors to give the user flexibility in constructing an object.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. use the Me keyword. One is a noargument constructor and one that accepts a String. the argument will hide the class-level variable.WriteLine("I am the manager. Even with constructors that accept different arguments. If the user does not know or does not want to pass a name value. For example. Look at the following: Public Class Manager Private nameField As String Public Sub New() 'give nameField a default value nameField = "Tony" System. For example. in the following Manager class there are two constructors.Console. then he/she can use the no-argument constructor.name = name System.Console.") End Sub End Class . oftentimes they execute the same code.WriteLine("I am the manager. 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.

Having the same set of code in two or more different places is not wise. you need to update it in more than one place. or you can create a constructor that accepts two arguments. For example. a Manager class has two fields: name and id. because if you need something changed. 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 . A common technique is to put the code in one constructor and call that constructor from the other constructors.id = 77 manager.Both constructors execute the following line: System.WriteLine("I am the manager.WriteLine("I am the manager.name = "Tony" With a constructor.New("Tony") End Sub Public Sub New(ByVal name As String) nameField = name System. the user code would be: Dim manager As Manager manager = New Manager() manager. Without the constructor.") And in a typical class. there could be multiple lines of code that need to be run in each of the class 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.") End Sub End Class Using a constructor for initialization also simplifies the code at the client side. 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.Console. 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.Console.

you have learned about constructors. Expectedly. Determining the type of object that can be created. There is no way the user can forget to set this value because the only constructor the Person class has requires a boolean. the only constructor the Person class has is a no-argument constructor. . such as in the following Person class.Without any explicit constructor. Public Class Person Private age As Integer Private male As Boolean Public Sub New(ByVal male As Boolean) Me. In brief. however. Restricting direct instantiation in the Singleton pattern (discussed in a separate article). will solve the problem. Summary In this article. there will be a method or property that the user can call to set the value of the male field. However. Using a constructor that accepts a boolean.male = male End Sub End Class Now the user of your class must supply a boolean for every Person object constructed. constructors can be used for: • • • Initialization. all objects constructed using the New keyword will have its male field False. therefore indicating that the Person is a female. If the user forgets to call this method. the resulting object can have invalid values.

let’s start with defining. table has properties besides behaviour. What does it mean? And what’s the difference between OOP and procedural programming? We’ll go through all these terms. that calculate the square. { 3. What’s wrong with this approach? Nothing wrong. Each table has only one property. return M_PI*$rad*$rad. Examples are for PHP.{ 13. but concept is the same in all object-oriented languages. we create variables for each property – height. without any objects. return $side*$side*0. Just take a look around. function calcTriangle($side) 7. Now we’ll create 3 functions. { 8. you focus on it’s behaviour (for example. We’ll demonstrate the difference of these approaches and advantages of the OOP over procedural concept. everything is fine. what OOP is and how it differs from procedural programming. that calculates height or that assembles it from the given dimensions).function calcCircle($rad) 12. weight. return $side*$side. 4. } 10. 11. function calcSquare($side) 2. you write function. Consider you have to program it. square. 9. For example. that we’re interested in – side for triangle and square and radius for rounded one. When using procedural approach.} Everything is fine until we have to print list of tables with squares like: Table name table 1 Type Squar e 0. Let’s try to do this with procedural approach. average: 4. (see formulas for equilateral triangle and circle) 1.95 m2 circle . width. However. } 5. Consider the following task.What is OOP (Object-oriented programming)? (5 votes.433. triangle and rounded. when we’re dealing with one table. 14.80 out of 5) Introduction OOP stands for Object-Oriented Programming. All that data – properties (variables) and behaviour (functions) describe the object from the real world – table. So. length. 6. We have to calculate square of every table. When following procedural paradigm. Procedural programming – the problem And now imagine if we have several table types – square. you see a table.

} 31.‘ m<sup>2</sup></td> 28. for ($i = 0. 2. 11. 20.echo ‘</table>’. switch ($tables[$i][0])//we have to define which type we’re dealing with 5.9).8). 1).‘</td> 26. 10. break. 4. In the array we have to specify the table type. } 12. 6. $square = caclCircle($tables[$i][1]).($i+1). array(‘square’. { 9. $tables = array( 2. break. 16. $i++) 3. 3. } 22. </tr> 29. $square = caclTriangle($tables[$i][1]). we need one more parameter in our array – the type of the table. <td>table ‘. case ‘circle’: 8.‘</td> 27. { 4. then check it and select the corresponding . 0. $s = sizeof($tables). //and call correct function for it 6. $i < $s. And now let’s program processing of these arrays (using the trick with for loop): 1. { 14. $square = caclSquare($tables[$i][1]).‘. 15.$square. { 19. <td>’.78 e m2 squar 1 m2 e … table 3 To process it.table 2 triangl 0. case ‘square’: 13. ). 0. array(‘circle’. echo ‘ 24. And adding it makes array a 2-dimensional one: 1. array(‘triangle’. case ‘triangle’: 18. Yes! We did it – created all the stuff we had to and it works fine.$tables[$i][0]. { 7. 5. 21. But take a look at this. break. 30. <td>’. } 17.7). <tr> 25. } 23. 0. array(‘circle’. echo ‘<table border="1" cellspacing="0" cellpadding="3">’.

Basically. by saying “object” we mean some abstraction of the real world object (not always real. 11. let’s start coding.//defining property 4. Create pot from clay (allocate memory according to the class definition) 3. } 9. } 10. And when we need the object of this class to work with. 1. { 7. And all of them are used even in this simple example. we instantiate it. return $this->radius*$this->radius*M_PI.{ . public function getSquare()//and method 6. we mentioned “classes”. what is object. And how about dealing with 10 table types? Adding each type requires adding new calculation function and changing the printing one. public $radius. what methods will work with his properties and how. 5. we can define 3 classes and use them all. that takes care of attributes initialization. Maybe you’ve heard of the 3 principles of the OO programming – Inheritance. Classes are “blueprints” for objects. now we have theory. So. OOP – solution And now we’ll take a look at the object-oriented solution. Class describes. Polymorphism. We’ll talk aabout them later. let’s see. Encapsulation. class CircleTable 2. volume=”big”) Little pot with water (Contents = “water”. It has properties: • • contents volume And objects of that class are: • • • Big pot with honey (Contents = “honey”. { 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).function. Yes. volume=”medium”) You also can imagine the process of instantiation of the pot as the sequence of operations: 1. volume=”little”) Medium-sized empty pot (Contents = “”. 8. that has some attributes (called properties or fields) and behaviour or actions (called methods). But before plunging into the OO world. what properties the object will have. you can imagine class as an empty pot.class SquareTable 12. So since object holds both it’s properties and behaviour. When developing. Take blueprint (class definition) 2. and the third step depends on the: • • Class definition – you can specify default values for the properties Class constructor – you can define special function. it may be an abstraction).

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. 2. 3. 4. 5. 6. 7. 8. 9. //creating the objects //in real application it is done much more smart //we’ll see how to do it better a bit later $tables[0] = new CircleTable; $tables[0]->radius = 0.7; $tables[1] = new SquareTable; $tables[1]->side = 0.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 objectoriented 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. echo ‘Table square = ‘. In PHP 5 constructor is defined as a special function. 10. { 12. And getSquare() itself is defined in the derived classes. 3. 13. It is a regular method. 6. } 14. Here is the code. Constructor is special function.$table->getVolume(). Singleton). 4. We’ve already mentioned them. 5. 2.g. { 3. but it can’t return any value.$table->getSquare(). which uses method getSquare(). that uses constructors for smarter object initialization: . constructors are private unless some design pattern is used (e. $table->radius = 0. this is inherited from parent class. that we didn’t define $height or method getVolume() in CircleTable class. $table->height = 0. it can be public. However. public function getSquare() 6. public function getVolume() 11. which is called TemplateMethod – we defined method getVolume(). 4.} And here is how it works: 1. public $height. Usually. Note. Don’t you think it’s very convenient? By the way.9.7. 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. 5. private or protected. return 0.‘ Table volume = ‘. named __construct. we used design pattern here. $table = new CircleTable. class Table 2. } 9. { 7. return $this->height * $this->getSquare(). that is called when object is created. 8.

return 0.class CircleTable extends Table 21. 40. public $side. public function __construct($h) 6. { 42.1. 55. 24. 5. 15. } 29. public function getSquare() 31.} 51. } 19. passing height there. 39. 27. public $height. { 32. 30. 18. { 26. $this->height = $h. } 34. public $side. public function __construct($r. { 12. { 48. 56. 49. 36. $h) 25. public $radius. parent::__construct($h). } 45. 33. return $this->radius*$this->radius*M_PI. } 14. 46. class Table 2.//setting the height 8. public function getVolume() 16.{ 54. 4. $this->side = $s. } 50. 13.} 35.//setting the side 44.{ 38. 23.//calling the constructor of the parent class.//setting the radius 28.//calling the constructor of the parent class.class TriangleTable extends Table 53.{ 22. $h) . $this->radius = $r. 10. { 7. 43. public function getSquare() 47. $h) 41. { 17. public function __construct($s. return $this->height * $this->getSquare(). 52. } 9. public function getSquare() 11. return $this->side*$this->side. passing height there. parent::__construct($h). { 3.class SquareTable extends Table 37. public function __construct($s.} 20.

0. For example. you may still use $table>radius to access it. class Table 2. public function getSquare() 12. 11. public function __construct($h) 6. { 18. { 64. { parent::__construct($h). $table = new CircleTable(0. { 7. 62. there are three access levels: 1. return $this->side*$this->side*0. } 10. 58. 14. } 61. 65. $this->height = $h. so we can correct definition of the Table class: 1. 16.} Here is how to create such classes: 1. $this->side = $s.57. 59. public function getSquare() 63.//calling the constructor of the parent class. } 15.//passing radius and height to the constructor 3. encapsulating some preprocessing.} So you can see.7. passing height there. Public – accessible both from class itself ($this->property) and from outside ($user->login) . Note. using constructors is VERY handy. The following usage is the same. 2. As we already mentioned. 5. if you have the properties public (like in this example). 19. we know that height can’t be negative. return 0. { 3. //restrict negative values 8.433.//setting the side 60. public function getVolume() 17. } 66. { 13. } 20.9). public $height. it just helps to initialize object attributes in one line of code. Attributes and methods access Finally.//setting the height 9. if ($h <= 0) $h = 0. 4. let’s take a look at the properties and methods visibility. return $this->height * $this->getSquare().

Since it is used only in getVolume() method. { 3. 16. //restrict negative values 13. Also.//setting the height 14. which is also defined in the Table class. 21. we’ll modify the Table class and make it’s $height property private. 5. 4. public function __construct($h) 6. not it doesn’t set the height itself. it delegates this to the special setter function. This will be used to modify height since we’ll not have access to it through $table->height. return 0. public function getSquare() 17. public function setHeight($h) 11. Private – accessible only from the class itself ($this->property. 24. { 12.} Note. } 15. } 25. public function getVolume() 22. property may be defined in current class or in the parent one) 3. what is returned and what is set and can ensure that object’s properties are always correct. we’ll not be able to access $height in CircleTable or TriangleTable. When using this definition. 8. } 20. Protected – accessible from the class itself and from it’s derived classes ($this->property. This is a good practice – to have attributes of an object hidden and have getter/setter methods to access it. we can either add getter method or make $height protected. which perform all validation. So here is UML and the code: 1. { 23. class Table 2. { 7. return $this->height * $this->getSquare(). Second variant allows to get the $height only within the derived classes (see protected access level above) . if ($h <= 0) $h = 0. { 18. Why? Because this way you control. we add a new method setHeight(). it should work fine. property should be defined in the current class) To demonstrate this in action. $this->height = $h. } 9. 19. $this->setHeight($h).2. 10. First variant will allow everybody to get the height. that we changed constructor. To enable this. private $height.

This is mainly used for the object initialization. Usually used for private or protected properties or for some kind of processing before returning. Encapsulation is an OOP principle. Design pattern is some standard proven solution to the common problem. Superclass is same as parent class or base class Subclass is same as derived class. that represents some attribute of an object. that describes some behaviour of an object. Constructor is a special method. look better.Glossary • • • • • • • • • • • • • • Class is a formal definition of some real object or it’s abstraction. Object is an instantiated class Property is a special variable. For example DB abstraction object. child class. Setter is a special method. Used for private or protected variables or for some additional validation. extended class Inheritance is an OOP principle. that returns property value. It contains definition of it’s both properties and methods. which is used to define some common behaviour in the base class and then extend it and use in the derived classes. (remember example with two programmers developing these table classes) Polymorphysm in an OOP principle. Singleton pattern solves the problem when we need some common resource in different places of an application. that sets property value. which allows different classes to behave differently when calling the same method. Sometimes it is called “member variable” Method is a special function. be better in support and future development . For example. Refactoring is the process of changing the source code to make it work faster. which used for hiding implementation details from the end-user. Getter is a special method. use better solutions. that is called when object is created.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.