advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Articles : JavaBoutique's Introduction to Java : Q and A :

Procedural vs Object-Oriented Programming

Q

I enjoyed your article in javaboutique. I like your use of examples that we can all relate to in the real world and then examples used in the programming world.

I am procedural programmer trying to re-train myself in the object-oriented way. Can you recommend a book/article that does the following:

  • explains the difference between classes and objects, methods, properties in simple terms - using examples like you did ( this is a hard concept for me to grasp )
  • gives examples of how to code simple programs procedurally and then re-write the code in the object-oriented method ( this would help me understand the differences between the 2 programming methodologies )

A

The best book I have ever read on Object Oriented Design is called "Thinking in Java" and as it so happens, is free for download at www.bruceeckel.com

Of course, even though it is free, I would buy the book at your earliest convenience as the print-out would be just as costly as buying the book.

You will never grow tired of re-reading Bruce's comfortable prose and you will learn something new on each re-read.

Also, over the next few months I'll be continuing my Java Tutorial and will be covering classes, objects, methods, etc.....

Nevertheless, I will try to give you a preview now so that you can get moving with your reading right away....


A class is a programmatic representation of an object.

Okay, that was a mouthful...let me take a step back.....

So you recall that an object is like a "thing". An object has "properties" such as hair color, weight, gender, and it has "methods" such as breathing, thinking, running.

Let's consider a specific example though. Let's consider a Button object.

A Button object has properties. It has a color. It has a label like "Click Me!". It has a width.

A button object also has methods. A button can be clicked. A button can have a mouseOver effect. And a button can be disabled so that it may not be clicked.

Well, that is cool and theoretically, it is not hard to imagine a Button as an "object". But seeing a button as an object is only half the battle of becoming an OO programmer.

You also need to know how to represent the object as computer code.

Well, a "class" is the programmatic representation of an object.

A class describes programmatically all the properties and methods of an object.

Consider the following pseudo code:

Class Button {

	color = red;
	label = "Click Me";
	width = 40 pixels;

	click() {
		Create a clicked-in 3D effect;
	}

	disableClick() {
		Don't allow anyone to use my click() method 
		until I am again enabled and turn my text gray;
	}

	enable() {
		Cool.  Allow people to click me.
	}

	mouseOver() {
		Make myself fuzzy looking whenever the user moves the mouse over me.
	}
}

So as you can see, the Button Class defines the properties and methods of an object programmatically. Some people like to call it the "blueprint" of an object. It specifies what objects look like generically.

Usually, you will "instantiate" an object by using its class.

For example, I might say:

myButton = new Button();

Now myButton is a full-fledged "object" that was molded into reality from the Button class cast. myButton can be said to exist whereas Button does not. Button is a generic definition. myButton is an actual implementation of the definition.

I can even do things like:

myButton.disableClick();

when I do so, I tell this living object (based on the Button class) to execute the code in its disableClick() method. Hopefully, I will have written code to make the button actually disable itself :)


Okay, now your second question....

Let's consider this little program written in a structural way:

	#!/usr/local/bin/perl
	my $a = 2;
	my $b = 3;
	my $c = $a + $b;
	print "The sum of $a and $b is $c";

	my $d = 3;
	my $e = 4;
	my $f = $a + $b;
	print "The sum of $d and $e is $f";
	exit;

Okay....pretty simple right? Now I could run this program and get the expected results. However, it is not a particularly elegant solution because I did a lot of "similar" work!

A better approach would be a modular structural design....

A well done, modular type structural program might be rewritten as:

	#!/usr/local/bin/perl
	print addNumbers(2,3);
	print addNumbers(3,4);
	exit;

	sub addNumbers() {
 		my $a = shift;
		my $b = shift;
		return ($a + $b);
	}

Notice that this second structural design is much better because it isolates functionality into subroutines.

There are two benefits.

  • First, you needn't duplicate operations over and over again. Granted, adding two numbers is not a complex operation... however, you'll find that your subroutines often contain 100s of lines of code that are shared between functions.
  • Second, since all code is only written once and is isolated into a single place, if you need to modify the code at some later date, you need only do it in one location!

    However, as I said in the tutorial, an even better methodology for efficiency is the object design. The program above might be written in an OO framework as:

    import AdditonObject;
    myAdditionObject = new AdditionObject(2,3);
    myAdditionObject.printSum();           // prints 5
    myAdditionObject.setNumbers(3,4);
    myAdditionObject.printSum();           /// prints 7
    

    and the AdditionObject might look like:

    class AdditionObject {
    	
    	int number1;
    	int number2;
    
    	new(int a, int b) {
    		number1 = a;
    		number2 = b;
    	}
    
    	setNumbers(int a, int b) {
    		number1 = a;
    		number2 = b;
    	}
    
    	printSum() {
    		System.out.println(number1+number2);
    	}
    }
    

    You'll note that there might seem to be more code to be written in an object framework. However, believe me, in the end it will save you hours and hours of time :)


    Selena Sol contributes to the JavaBoutique's Introduction to Java. Selena curently works for Barclays Capital in London, one of the leading global investment banks in Europe and has worked as a software developer for the National Center for Human Genome research, Microline Software, Neuron Data, and Electric Eye in Singapore. Selena is perhaps best-known for creating the Public Domain Web Script Archive (Extropia) and writing several books on Web Programming (Perl, CGI, Java).
    Email: selena@extropia.com

    How to Add Java Applets to Your Site

    New on the Java Boutique:

    New Review:

    Time Management Made Easy with the Quartz Enterprise Job Scheduler
    Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

    New Applet:

    Reverse Complement
    Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

    Elsewhere on internet.com:

    WebDeveloper Java
    Lots of Java information on webdeveloper.com

    WDVL Java
    Thorough Java resource at the Web Developer's Virtual Library.

    ScriptSearch Java
    Hundreds of free Java code files to download.

    jGuru: Your View of the Java Universe
    Customizable portal with online training, FAQs, regular news updates, and tutorials.

  •  DevX Skillbuilding from IBM developerWorks
     RIA Run Contest: Build Next-Gen Apps in Microsoft Silverlight 2
     Avaya DevConnect Center
     Intel Go Parallel Portal
     Internet.com eBook Library
     Microsoft RIA Development Center
     Destination .NET
    XML error: not well-formed (invalid token) at line 53
    advertisement
    Receive Articles via our XML/RSS feed
    Receive Articles via our XML/RSS feed

    JavaBytes
    Internet Cyclone
    This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

    SaaS Tool Offers Custom Database Development
    Microsoft’s Automated Agent: Can We Talk?
    Borland Finally Sells CodeGear
    Red Hat Heads For The JON 2.0
    Out with the Old, in with the New at JavaOne
    Trolltech Expands WebKit Footprint
    Oracle: Eating its Own Open Source Food
    Big Money and Open Source May Not Compute
    Open Source Embrace Gives Sun New Fans
    NetBeans, OpenSolaris Also in Spotlight at JavaOne

    Taming Trees: Building Branching Structures
    Clean Up Function Syntax Mess with decltype
    Sutter Speaks: The Future of Concurrency
    INTEL SCAVENGER HUNT, LENOVO X300 AND APPLE IPOD TOUCH GIVEAWAY (the "Giveaway")
    Comparing Multi-Core Processors for Server Virtualization
    Intel® Desktop Business Computing Solutions
    Intel: What Downturn?
    Managing the Evolving Data Center
    Implement Drag and Drop in Your Windows Forms Applications
    Processing Linked Web Data with XSLT

    Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES