Introduction to OOP (object-oriented programming)

by iatanasov 28. April 2007 15:26

Encapsulation is one of the most important aspects of object-oriented languages. The rule of encapsulation is one of keeping things private or masked inside the domain of an

object, package, namespace, class, or interface and allowing only expected access to pieces of functionality. We use the rule of encapsulation in almost every aspect of OOP

(object-oriented programming). This rule allows us to build programs like facades, proxies, bridges, and adapters. It allows us to hide with an interface or class structure some

functionality that we do not wish to be publicly or globally known. It allows us to define scope inside our programs, and helps us to define and group modules of logic. It provides

ways to allow objects to communicate without that communication getting either too complex or too entangled. It provides rules of engagement between different code bases, and helps us decide what functionality can be known and what needs to be hidden. Think of encapsulation like your mortgage company. You send off your mortgage payment every month and get a statement back showing your loan data. How your payment is applied and handled inside the mortgage company’s accounting department is unknown to you, but you can see evidence of it in your statements and the slowly reducing loan debt against your house. The accounting processes behind how this process works is invisible to you. It exists behind the business facade of the mortgage company. The company has processes and rules based on laws and business practices to guarantee that your money is safely deposited and applied to your loan. You know it works; you just don’t know or even care how it works, as long as it works as expected and returns the expected results.

Working with encapsulation within your programs is very similar to the example we just read. Let’s say we want to build a class that applies your mortgage payment to your loan. We obviously want to allow limited access to this class, since it handles money and sensitive information, so allowing every process around it to access every method inside it would not be a good idea. So instead we choose two methods to make public and mark the access of the remaining methods private. One of the public methods is a method to apply the payments, including the money and account number as input parameters and outputting the loan amount left after the payment is applied. The other is a method to return amortized data surrounding the payment plan.



class CustomerPayment

{

public double PostPayment(int loanId, double payment)

{

.....performs post of payment to customer account


}

public ArrayList GetAmortizedSchedule(int loanId)

{

...returns an amortization schedule in array

}

}



Notice that the two methods in the code above are visible as public. We can assume that the CustomerPayment class has many other methods and code to help perform some of the functions of its two public methods, but since we cannot access them outside the class code they are in effect invisible to any other classes in the code domain.

This gives us proper encapsulation of the class methods, allowing only the required methods to be accessed. Thus, the method of encapsulation for this class is to allow only the two methods, PostPayment() and GetAmortizedSchedule(), to be accessed outside the class.


Polymorphism is another important aspect of objectoriented programming. The rule of polymorphism states that classes can be altered according to their state, in effect

making them a different object based on values of attributes, type, or function. We use polymorphism in almost every coding situation, especially patterns. This rule gives us the power to use abstraction and inheritance, allowing inherited members to change according to how they implement their base class. It also allows us to change a class’s

purpose and function based on its current state.


Polymorphism helps interfaces change their implementation class type simply by allowing several different classes to use the same interface. Polymorphic declarations of specific implementations of classes with a common base or interface are extremely common in object-oriented code. To better understand polymorphism we can think of an example of using an interface and a group of classes that implement the interface to perform different functionality for different implementations.


An interface is a type of code that is not a class, but acts together with different classes to define a common link, which would not be possible otherwise. It is simply a protocol in object-oriented languages that exists between classes and objects to provide an agreed upon linkage.


Let’s take a look at an example that illustrates the role polymorphism plays in a relationship between classes without a common base class and an interface designed to allow some

common definitions between these classes. We start out with some common if...then...else code as we might see in any language, either scripting or object. Our mission is to use the aspect of polymorphism to make this code more flexible.


if(IsAntiqueAuto)

AntiqueAuto auto = new AntiqueAuto();

int cylinders = auto.Cylinders();

int numDoors = auto.NumberDoors();

int year = auto.Year();

string make = auto.Make();

string model = auto.Model();

}


The first thing you need to answer is why do we want to change this code? The answer might be one of portability: You wish to have many car types and pass the logic of creating them via the class itself, rather than via a logical Boolean statement. Or you might wish to make sure all auto classes have the same methods so your code accessing the object always knows what to expect. In the code example below we can see an interface, IAuto, and below it some classes that we have modified to implement this interface. We can assume that each class also implements the interface’s methods, each functioning in its own way, returning values according to the logic specific to the implemented methods on each class.



public interface IAuto

{

int Cylinders();

int NumberDoors();

int Year();

string Make();

string Model();

}

class AntiqueAuto : IAuto....

class SportsCar : IAuto....

class Sedan : IAuto.....

class SUV : IAuto.....

To understand how polymorphism acts in the interface-class relationship, let’s look at some code where different class types are created via the IAuto interface. First, we see how

one of the classes that implement the interface methods can use the interface to define each class’s methods as independent logic. Let’s look at an example of one of the classes

we saw in the previous code example. Notice that each of the methods that are present in the interface are represented in the AntiqueAuto implementation and return values specific to its type of auto. This is mandated by the compiler, to ensure all methods in the interface are implemented in the class to determine common functionality between this class and others that implement the IAuto interface. This defines one aspect of polymorphism, in that by changing its underlying class type, the interface can allow different functionality from each class implementation.


class AntiqueAuto : IAuto

 

{

public int Cylinders()

{

    return 4;

}

public int NumberDoors()

{

    return 3;

}

public int Year()

{

    return 1905;

}

public string Make()

{

return "Ford";

}

public string Model()

{

    return "Model T";

}

}


Now, when looking at another class that implements the same interface, we see it has a completely different implementation of each of the interface methods:


//another implementation of IAuto

class SportsCar : IAuto

{

public int Cylinders()

{

    return 8;

}

public int NumberDoors()

{

    return 2;

}

public int Year()

{

    return 2005;

}

public string Make()

{

    return "Porsche";

}

public string Model()

{

    return "Boxter";

}

}



Next, we instantiate the AntiqueAuto class as an instance of the IAuto interface and call each of the interface methods. Each method returns a value from the methods implemented on the AntiqueAuto class.

IAuto auto = new AntiqueAuto();

int cylinders = auto.Cylinders();

int numDoors = auto.NumberDoors();

int year = auto.Year();

string make = auto.Make();

string model = auto.Model();

If we changed the implemented class to SportsCar or another auto type, the methods would return different values. This is how polymorphism comes into play in class relationships. By changing the class type for a common interface or abstraction, we can change the functionality and scope of the code without having to code if... then...else statements to accomplish the same thing.

IAuto auto = new SportsCar();

int cylinders = auto.Cylinders();

int numDoors = auto.NumberDoors();

int year = auto.Year();

string make = auto.Make();

string model = auto.Model();

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

object-oriented programming

Related posts

Comments

October 10. 2009 18:53

Gravatar

Hello, This is my first time visiting here. Your blog is a nice,I thought I would leave my first comment. :)

Kenali dan Kunjungi objek Wisata di Pandeglang us

October 21. 2009 06:35

Gravatar

Nice resource. rss feed added

cash loans us

November 18. 2009 17:58

Gravatar

Nice resource. rss feed added

paydayloans us

January 13. 2010 09:24

Gravatar

Thanks for the information. A very informative one I was looking for it. Keep up the good work and would like to hear more from you.

Extenze us

January 21. 2010 11:26

Gravatar

well

friendly themes code structure us

January 26. 2010 20:31

Gravatar

When it is dark enough, you can see the stars.

payday loans us

January 28. 2010 14:46

Gravatar

Thoughts lead on to purposes; purposes go forth in action; actions form habits; habits decide character; and character fixes our destiny.

Loans in VA us

February 18. 2010 23:56

Gravatar

Nothing can add more power to your life than concentrating all your energies on a limited set of targets.

colon cleanse us

February 20. 2010 07:21

Gravatar

This is a pretty fluent writing style you have here. keep up the good work.

Coupons us

February 25. 2010 17:34

Gravatar

Your blog is so informative … keep up the good work!!!!

pay day loans

February 27. 2010 08:16

Gravatar

I am not really sure if best practices have emerged around things like that, but I am sure that your great job is clearly identified. I was wondering if you offer any subscription to your RSS feeds as I would be very interested and can?t find any link to subscribe here.

cash advance

February 28. 2010 09:28

Gravatar

좋은 게시물 주셔서 감사합니다

Oven Parts us

February 28. 2010 12:11

Gravatar

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It?s the old what goes around comes around routine.

Acne treatment

March 4. 2010 13:48

Gravatar

I usually don’t post in Blogs but your blog forced me to, amazing work.. beautiful … Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

cash payday loan

March 7. 2010 04:06

Gravatar

my God, i thought you were going to chip in with some decisive insght at the end there, not leave it with ‘we leave it to you to decide’. Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

paydayloans

March 8. 2010 20:52

Gravatar

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

bad credit loans

March 13. 2010 16:24

Gravatar

I just hope to have understood this the way it was meant

Stretch mark removal

March 14. 2010 12:23

Gravatar

Hvala vam za dobar post puno hvala

general electric cooktop us

March 18. 2010 03:53

Gravatar

I received my first <a href="http://lowest-rate-loans.com/topics/credit-loans";>credit loans</a> when I was 32 and this supported me very much. Nevertheless, I require the financial loan once more time.

business loans ca

March 26. 2010 12:01

Gravatar

Your weblog includes a genuinely cool pattern. That becoming said http://wordpress.org/extend/plugins/backup-content-as-txt/ the details here is totally free and is of high-quality. I'm subscribing to your feed right now.

Jamie Lemaire cn

March 26. 2010 13:37

Gravatar

I was very pleased to find this site.I definitely enjoying every little bit of it and http://odadeo.com/people/3053 I have you bookmarked to check out new stuff you http://depressionselfhelp.blog.com/the-importance-of-drinking-water-filter/ post.

Marianela Cilenti cn

March 26. 2010 23:34

Gravatar

Hey, i've been reading this blog for a while and have a question, maybe you can help... it's how do i add your feed to my rss reader as i want to follow you. Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

nail fungus home remedies

March 28. 2010 03:00

Gravatar

Hey - nice blog, just looking around some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?

easy payday loans

March 30. 2010 17:51

Gravatar

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here. Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

hpv genital warts

April 1. 2010 23:31

Gravatar

Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

used auto loans

April 3. 2010 06:06

Gravatar

That is some inspirational Never knew that opinions could be this http://www.blogigo.com/changemylife/need-say-somthing-about-Aquasana-drinking-water-filter/10/ varied. here.

Young Buchetto cn

April 3. 2010 06:21

Gravatar

Glad to see your website! http://www.slideshare.net/jkljkl520/drinking-water-filter wish you have a great day! http://www.scribd.com/doc/29082722/Drinking-Water-Filter Thanks for this blogging http://www.docstoc.com/docs/31977803/Drinking-water-filter I will bookmark again.

Blaine Mahone cn

April 5. 2010 16:20

Gravatar

Hello. Great job. I did not expect this on a Wednesday. This is a good story. Big thanks for the useful info i found on Introduction to OOP (object-oriented programming).

new cellulite treatment us

April 6. 2010 08:07

Gravatar

It does seem that everybody is into this kind of stuff lately. Don’t really understand it though, but thanks for trying to explain it. Appreciate you shedding light into this matter. Keep it up

smoked turkey recipe cn

April 6. 2010 20:14

Gravatar

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It's always nice when you can not only be informed, but also entertained! I'm sure you had fun writing this article.

bakery cake recipe cn

April 8. 2010 14:53

Gravatar

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

home drinking water filters us

April 10. 2010 05:16

Gravatar

Awesome thread with thoughtful contributions on oop.
I want to read more but I need to get to work!

Steven za

April 11. 2010 07:41

Gravatar

I am not really sure if best practices have emerged around things like that, but I am sure that your great job is clearly identified. I was wondering if you offer any subscription to your RSS feeds as I would be very interested and can?t find any link to subscribe here.

easy cash loans us

April 13. 2010 10:27

Gravatar

Hmmm, thanks for this info on oop. This website is proving to be a great help for my own pursuits
Graci

Christine my

April 14. 2010 15:58

Gravatar

I'm interested in learning more on oop.
Thanks for this info

Andrew my

April 25. 2010 04:56

Gravatar

e

black laminate flooring us

May 3. 2010 01:52

Gravatar

As a Newbie, I am always searching online for articles that can help me. Thank you

unsecured personal loan bad credit us

May 13. 2010 23:43

Gravatar

This is a excellent post, but I was wondering how do I suscribe to the RSS feed?

Valve Ball us

May 14. 2010 07:06

Gravatar

you can reach my RSS here - http://feeds.feedburner.com/netFire

Ivan Atanasov bg

Comments are closed

Powered by BlogEngine.NET 1.1.0.7
Theme by Mads Kristensen

About the author

Ivan Atanasov - web developer
E-mail me Send mail Subscribe Feed

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2012 it-coder.com

    Sign in