Wednesday, April 15, 2009

CSS 2008: JavaScript, JSF, and Domain-Driven Design

The Colorado Software Summit has posted four more presentations from Colorado Software Summit 2008. There are two presentations related to Domain-Driven Design (DDD) in Dan Bergh Johnsson's presentations "The Power of Value — Domain Driven Design and Value Objects" and "Object Orientation, Domain Driven Design, and the Honour of the Programmers' Guild." The other two newly released CSS 2008 presentations, by Bryan Basham, are on JavaScript ("Becoming a JavaScript Wizard") and JavaServer Faces ("Mastering JavaServer Faces"). There is currently a link to the PDFs of these four presentations on the main page or they can be downloaded from the Colorado Software Summit 2008 agenda page.

Monday, April 13, 2009

Exporting POJO via JMX and Groovy

In several previous blog postings, I have described how to expose Java classes via Java Management Extensions (JMX). In particular I have described exposing non-JMX-aware classes via JMX using direct ModelMBeans, via the Spring Framework, via Apache Commons Modeler, and via EasyMBean. Another approach for easily exposing a non-JMX class as a JMX MBean is to let Groovy do the work.

Groovy JMX Builder is now included in the core Groovy distribution and so no longer requires a separate download. I am using Groovy 1.6.1 for the examples in this posting. The GroovyDoc-based documentation for the groovy.jmx.builder package is included with the Groovy 1.6.1 API documentation.

To demonstrate use of Groovy and Groovy JMX Builder to expose a POJO as a JMX MBean, I will first start with a POJO. This class is shown next (I've left out comments for brevity):

HelloJmx.java


package dustin.examples;

public class HelloJmx
{
private String salutation = "Hello";

public HelloJmx() {}

public String hello(final String addressee)
{
return this.salutation + ", " + addressee;
}

public String getSalutation()
{
return this.salutation;
}

public void setSalutation(final String newSalutation)
{
this.salutation = newSalutation;
}
}


This simple Java POJO can be exposed easily as a JMX MBean via Groovy as shown in this Groovy code sample.

exportHelloWorldViaBasicGroovyJmx.groovy


import dustin.examples.HelloJmx
import groovy.jmx.builder.JmxBuilder

JmxBuilder jmxBuilder = new JmxBuilder()
def hello = new HelloJmx()
jmxBuilder.export { bean(hello) }

println "Use JConsole or VisualVM to see exposed Calculator"
println "Press ENTER to exit."
Console console = System.console();
console.readLine()


With Groovy installed on my machine, running this script is easy as shown in the next screen snapshot:



As the screen snapshot indicates, running the Groovy script is very similar to running the Java launcher to run a Java application.

I can run a general JMX client such as JConsole or VisualVM against this Groovy-enabled JMX-exposed application. The next screen snapshot shows how to connect to the Groovy enabled JMX-exposed application on the local machine (it lacks an obvious label, but it is the process that is not JEdit and not JConsole itself).


Once I connect to this Groovy/JMX-enabled application, I can view its MBeans as shown in the next screen snapshot.



Although the HelloJmx class provided a setSalutation method, the Salutation attribute is read-only as shown in the above screen snapshot. This is the default behavior of Groovy's JMX Builder. In addition, the ObjectName of the bean is the default-based jmx.builder.ExportedObject:type=dustin.examples.HelloJmx@11845181.

It would be nice to customize the JMX support a little more. This is easily done with Groovy JMX Builder as I will demonstrate in the remainder of this blog post.

To expose the "setter" for the Salutation attribute in the HelloJmx example, I need to make it "writable." Editing the Groovy script to explicitly state descriptive information about how the Salutation attribute should be exposed makes this possible and is demonstrated in the next code listing.

exportHelloWorldViaAdvanceGroovyJmx.groovy


import dustin.examples.HelloJmx
import groovy.jmx.builder.JmxBuilder
JmxBuilder jmxBuilder = new JmxBuilder()
def hello = new HelloJmx()
jmxBuilder.export
{
bean(target:hello,
name:"dustin.example.hello:type=GroovyJmx",
attributes: [
"Salutation":[desc: "Salutation to use with name.",
readable: true,
writable: true,
defaultValue:"Hello"] ],
operations: "*")
}
println "Use JConsole or VisualVM to see exposed Hello World"
println "Press ENTER to exit."
Console console = System.console();
console.readLine()


In the above Groovy script, I overrode the default ObjectName with the new name of "dustin.example.hello:type=GroovyJmx" ("type" gets special treatment in JConsole). I also expressed more details about the Salutation attribute, including specifying that it is writable. Two screen snapshots showing the results of the attribute metadata description and the customized object name are shown next:






Conclusion

Groovy provides another handy approach for exposing Java objects via JMX for management and monitoring.

Saturday, April 11, 2009

Benefits of Using Open Source: Potential Versus Realizable

There are many advertised benefits of using open source. These potential and advertised benefits include business flexibility, freedom/liberty/libre, (often) no/reduced license costs (gratis), improved security through disclosure, improved testing in real situations, improved code review by multiple reviewers (many eyeballs), high quality, the ability to learn from the code (both about how a particular product works and general coding principles), and even betterment of society. However, I have found that the realization of these potential benefits of open source depends largely on the open source product itself. Indeed, there are many open source projects that enjoy very few of these benefits.

In the remainder of this blog posting, I will look at how the nature of a particular open source product often determines the ability to realize the general advertised benefits of open source associated with that product.

Business Flexibility

It has been argued that an advantage of open source is greater flexibility in switching implementations (no vendor lock-in). However, the ability to switch implementations often depends more on the degree to which a product (open or closed) is based on standards than on whether the product itself in open source or closed source. It is certainly true that a closed source standard-compliant implementation will be easier to switch out from than a non-standard open source implementation. The standards reference implementations in the Java space are open source and therefore are good examples of open source products that do support great freedom to switch out implementation. For example, one can, in theory, easily switch from Tomcat or GlassFish to WebSphere or WebLogic or switch the other way. This does not necessarily have anything to do with Tomcat and GlassFish being open source, but instead has to do with all these products (including the closed-source WebSphere and WebLogic) implementing the same standard.


No Cost / Free Beer / Gratis

Some definitions of open source explicitly require that open source software be freely available without any limitation or cost (free beer). However, others aren't as concerned about the "free beer" aspect as they are about the "free speech" aspect of open source. Although most products that are advertised as open source do seem to be available for no cost, this should not be assumed without careful reading of the product's license. Moreover, there are many proprietary and closed source products that are also free of charge. These include products such as JDeveloper (a Java IDE that is not open source but is available without charge), Oracle Database Express Edition, Adobe Reader, Flash Player, Microsoft Internet Explorer, etc.

As another example, I was using Flex regularly back in its closed-source-but-freely-available days as Flex 2 and really liked it even then. Although I was excited to see Flex 3 open sourced, it really didn't change my use of Flex much in terms of its daily use. I was honestly more interested in Flex 3's new features than the fact that it was now open source.

As I have posted about earlier, I believe that open source contributors have a right to expect compensation for their work and creativity. This compensation for open source contributors often comes from support and service contracts, sales of documentation, sales of related books and articles, and consulting sales.

In the end, price may be a benefit of a particular open source product over a particular closed source product, but there are usually many factors to consider such as the total cost of using each product (training, service contracts, etc.). With freely available closed source products in the mix, it is certainly possible to find a situation in which use of the open source product is no cheaper than using its closed source alternative.


Freedom / Free Speech / Libre

The ability change the code is something that certainly differentiates open source from closed source. However, even this obvious differentiating benefit deserves closer examination when determining how much of this benefit is actually realizable. One consideration is that some open source licenses have restrictions on changes to open source products that are included in distributed products. In some cases, these restrictions may be deemed unacceptable, making this particular benefit unrealizable for that organization with that particular open source product.

A second consideration is to truly evaluate the likelihood of actually changing the open source product's code to suit one's own needs. It may be that an individual or organization has no qualms about this and, in such a case, they will be able to readily realize this benefit. However, if the individual or organization is reluctant to actually make changes to source code of an externally-provided open source product because of needs such as greater testing, greater maintenance costs, additional efforts to integrate with future versions of the product, and so forth, then this benefit may lose its degree of realization.


The Many Benefits of 'Many Eyes'

Several of the benefits commonly associated with use of open source products depend on the presumption of "many eyes" reviewing open source code. It is argued that open source products are inherently more secure than closed source products because there are many more reviewers of the source code. The argument of many more reviewers of code also leads to the advertised benefit of better code reviews and better quality in open source products. With many more users of the open source product, the argument continues that open source is better tested than proprietary software. Finally, another benefit often attributed to open source is a greater likelihood of having bugs fixed quicker. All of this, however, hinges on the presumption that there are indeed 'many eyes' reviewing and using the open source product. What happens when that is not the case? What happens if no one is actively supporting a particular open source product? Do these benefits still apply?

One definite advantage of open source is that one always can look at the source code directly. However, I think many end users of open source don't actually look at source code that often, but instead rely on the assumption that other users of the open source will have reviewed the code, looked for security holes in the code, and run the code in their applications. This assumption is more likely to be correct or appropriate for open source products with large communities than it is for open source products with very small communities.

Open source projects that enjoy large communities are more likely to allow potential open benefits to be realizable benefits. Large communities tend to mean "many eyes," which in turn can lead to less likely security holes, to more highly reviewed code, and to code used more frequently in a wider variety of situations and loads.

At the other extreme are the open source projects with a community of one, the open source project founder. It is unlikely that these open source products with one creator (who is also the product's only user) have anywhere near the amount of review and testing as most proprietary products.

Several people have pointed out that open source does not necessarily make something more secure. This is covered in Many Eyes, But How Many Brains?. A similar argument against stating that open source always means higher quality software is made in Open Source Does Not Make Better Code. Better Programmers Make Better Code.


Learning from the Code

This is probably the generally advertised open source benefit that most easily translates to a realized benefit. Having access to source code can be instrumental in learning how the code works. Viewing the source code can help one better understand how to use the library it underlies. For example, when Michael Martin and I were writing the article Visualize Your Oracle Database Data with JFreeChart, we figured out some minor details of the JFreeChart API by looking at JFreeChart's source code.

Having access to the source code can be useful when debugging or working on performance tuning. It can also be useful for learning how to accomplish certain things in your own code. I remember learning HTML (along with many bad habits) in the early nineties by viewing the source code of others' web pages.


All Open Source is NOT Equal


Even though I use many great open source software products and know of many more, there are many times that number of open source products out there without much of a community and without much to offer yet. It is not appropriate to lump the good and the bad together, but instead good open source should be differentiated from bad or immature open source. When considering how many immature or unused open source projects are out there, consider that SourceForge alone has more than 230,000 software projects (as of February 2009). There are several really good and useful projects on SourceForge, but the degree of value, maturity, or even level of support per project varies greatly. This is true across many open source repositories.


Conclusion

Nothing in this blog posting should be interpreted to mean that I'm against open source. On the contrary, I love using strong open source products with large, vibrant, and active communities. My only point of this posting is that it is too simplistic to argue that open source is always better than closed source. Instead, like most things in life, it is more complicated than that. It really depends on the individual products being compared. The state of being open or closed source can be considered as one of the criteria in selection, but should not normally be the deciding factor. All else being equal (or even close to equal), I typically favor open source products, but I don't blindly select an open source product over its closed source alternative simply because one is open source and one is closed source.

Most of the products I choose to use regularly are open source (Java, Flex, AIR, BlazeDS, OpenLaszlo, Ant, NetBeans, Eclipse, log4j, JUnit, Spring Framework, GlassFish, JEdit, JFreeChart, Ruby on Rails, Tomcat, Apache HTTP Server, various flavors of Linux, Firefox, and on and on). Nearly all of them have very large and active communities. Most of them also have strong sponsors (such as Apache Software Foundation, Sun, Adobe, SpringSource, Oracle, etc.) who provide staffing (in many cases) and common direction for them.

All open source is not created equal. Some open source products are really good; others aren't very good at all. In the end, my favorite open source products are the ones that can take on any closed source alternatives toe to toe and come out equal to or ahead even without considering that they happen to be open source. In those cases, I am typically indirectly and perhaps even unknowingly enjoying the realized benefits of the open source nature of the product without focusing on that open source nature. After all, it matters more to me what works best, works most efficiently, is easiest to use and maintain, is most tested, and is most easy to switch away from if needed. Open source is often a characteristic of products that meet these expectations, but not all open source products do allow these potential benefits to be actually or easily realized.

The one benefit you can count on in just about any major open source product is the ability to see and, in most cases, change the source code if necessary. This often may not be a very attractive scenario, but it is the one benefit that can be always be realized with open source and never realized with closed source.

Tuesday, April 7, 2009

More Movies Quotes Applied to Software Development

I previously blogged on Classic Movies Quotes Applied to Software Development. That may have been my favorite blog post to write because it combined two things I really enjoy in combining software development and movies. That blog post was also unique in that it is the only one I am aware of to be referenced in the online CNN Entertainment section. More specifically, the JavaWorld-syndicated version of my blog post was referenced in the article You' talkin' to me? Film quotes stir passion.

To limit the previous posting to ten movie quotes, I had to exclude several favorite movies and quotes. In this posting, I outline ten additional movies quotes that can be applied to software development. As before, the only criteria is that the quotes come from movies I have seen and enjoy. The movies do not have to be technically themed and, in fact, my preference is for more general quotes that can be applied to software development.


1. I've just sucked one year of your life away.

The quote from 1987's The Princess Bride perfectly describes how one might feel after a year on a particular software development gig or project that just seems to drain the life away. On the wrong project, it can feel like this even if the actual time spent is less than one year.

I included a quote from The Princess Bride in my earlier post on movie quotes applied to software development. The popularity of this highly quotable movie is evidenced by its current #173 ranking in the IMDb Top 250 (one of my very favorite movies, 1994's The Shawshank Redemption, is #1 on that list). Anecdotally, it seems that this movie may even more popular than that among software developers.


2. The code is more what you'd call 'guidelines' than actual rules.

These words by Captain Hector Barbossa to Elizabeth Swann in the surprisingly entertaining 2003 movie Pirates of the Caribbean: The Curse of the Black Pearl refer to the pirate's code, but sometimes developers might be attempted to see requirements as guidelines rather than requirements. This is generally not a good idea, however, assuming that requirements have been accurately collected from customer input. Meeting the requirements generally means making the client happy. Although exceeding client expectations is often a good practice, implementing things they did not ask for at the expense of things they did ask for is usually anything but a good idea.


3. Takes a big man to admit when he's wrong. I am not a big man.

This quote from Chevy Chase's Fletch character (calling himself Elmer Fudd Gantry in the sequel Fletch Lives) reflects a feeling (and often action) that is familiar to anyone who has made a mistake in software development. It often does take a big person to admit when he or she is wrong. In fact, many of us often aren't big enough to do it. This is what makes blog postings like How and Why I Missed the Boat as a Developer and The * Stupidest Things I Have Done in My Programming Job both rare and refreshing.


4. It's not the years, honey, it's the mileage.

This response from Indiana Jones to Marion Ravenwood's statement "You're not the man I knew ten years ago" in 1981's Raiders of the Lost Ark is a reminder that it is often the type of experience that we have in software development that is more important than the years of experience. For example, a software developer who works with different problems and solutions and with different approaches for seven years is very likely to have better experience than the developer who works on the same problem with the same language repeatedly for the same seven years. It is what is done during that time, rather than the time served itself, that matters in terms of learning from experience.

Raiders of the Lost Ark is currently ranked #18 in IMDb's Top 250. I agree with the review comment of Dan Grant on this movie: "There will never be another film like Raiders."


5. I don't know, I'm making this up as I go.

Raiders of the Lost Ark is so good (see last quote) that I'm going to break my own rule (don't tell the Transporter) and use two quotes from that movie in this same blog posting. When Sallah questions how Indiana Jones is going to get the Ark of the Covenant off of the truck headed for Cairo, Dr. Jones makes this funny (but seemingly correct) statement. In the fourth movie of the Indiana Jones franchise (2008's Indiana Jones and the Kingdom of the Crystal Skull), Marion Ravenwood reiterates this quality in Dr. Jones to their son Mutt when Mutt asks "What's he [Indiana Jones] gonna do now? " and Marion responds, "I don't think he plans that far ahead."

In software development, we like to have a good idea of what we're designing and developing. However, I think most of us must admit that there are times when we don't realize that we didn't think of something or had not considered something until we run into the issue. This is one of the reasons it can be advantageous to begin implementing ideas early. While this approach always seems to work for Indiana Jones, we have to be more careful to mix it with appropriate planning. The agile principle agile designs are emergent seems to fit this quote to some degree.


6. If you're good at something never do it for free.

This statement from Heath Ledger's The Joker in 2008's The Dark Knight can often apply to the best software developers. This is one of the reasons that I do not begrudge open source contributors from making money through selling of documentation, selling of services, selling of consulting, selling of books, or other methods of earning some monetary compensation for their contributions.

Incidentally, The Dark Knight is another example of how "winning" can be measured in multiple ways. Although The Dark Knight was not even nominated for the Academy Award (Oscar) Best Picture in 2008 (and thus could not win the prize), it won in a different (and to many people much more important) way, dominating the box office for the year. It went further than that by earning the #6 ranking in IMDb's Top 250 (all time) and grossing the second most box office receipts in the United States (fourth worldwide). Although we all like to make quality software and feel like we're making a difference, it is also nice to be compensated for our effort, creativity, and time.


7. Rule #1. Never change the deal.

In 2002's The Transporter, Frank Martin is successful because he follows strict rules religiously. The whole plot of the movie essentially develops when Frank breaks his own rule.

There are many times that we wish Frank's first rule ("never change the deal") could be enforced. However, it seems like the opposite is almost always true: the rules or requirements change frequently. One of the explanations for the rise in popularity of the agile method of development is its focus on ideas such as responding to change over following a plan and customer collaboration over contract negotiation. These are realizations that deals do get changed and requirements do change rather we like that or not. Still, it sure sounds nice if we could follow Rule #1 more strictly sometimes.


8. Remember you told me to tell you when you were acting rudely and insensitively? Remember that? You're doing it right now.

It is perhaps not coincidence that the character this quotation applies to (Malvin) in 1983's War Games is a computer programmer. What is surprising is that Malvin even knew he had a problem acting "rudely and insensitively" and cared enough to ask Jim to tell him when he was acting like that. My experience, fortunately, has been that most software developers are easy to work with, but there is a small number of developers that act "rudely and insensitively." They either aren't aware of how rude they can be or, if they are aware, don't really care.


9. I'm trying to free your mind, Neo. But I can only show you the door. You're the one that has to walk through it.

It is important for more experienced developers to help less experienced developers through roles as mentors. I have written before about software craftsmanship and about the artisan teaching the apprentice. These are vitally important, but in the end it is the effort of the apprentice that matters most. No matter how much the master craftsman tries to help, the apprentice must make the effort to learn lessons and gain knowledge for the relationship to work.

This quotation comes from the 1999 movie The Matrix, which is wildly popular among software developers, but is also popular in general as evidenced by its 29th ranking in the IMDb Top 250.


10. You've got to ask yourself one question: Do I feel lucky? Well, do ya, punk?

This is a classic quote in a classic moment said by a classic actor (Clint Eastwood) in a movie classic (1971's Dirty Harry). There are many times in software development when we may well ask ourselves this question, "Do we feel lucky?"

There are many times when we think of something that we think will work well, but we may not always be certain of its outcome. The answer to this question determines if we are willing to pursue the action with uncertain consequences or stick to a safer and more predictable route with less potential. Even the Google search engine has a button "I'm Feeling Lucky" that will automatically forward the person requesting a search to the first web page on Google's returned list of matching web sites.

The observation that potentially greater return comes from taking greater risks has been discussed in financial context, in social contexts, and even emotional contexts. Because greater risk can mean greater failure instead of greater success, it can be a difficult decision when trying to answer the question, "Do I feel lucky?"


Conclusion

As evidenced by the CNN article referencing my first blog posting on movie quotes applied to software development, quoting of movie quotes is a widely popular cultural phenomenon. In software development, we use design patterns, acronyms, and fancy words to communicate wider ideas and movie quotes are often used the same way.

I also want to thank acquaintances (and especially Bill Jackson) for providing input on this second set of movie quotes that can be applied to software development.

Sunday, April 5, 2009

IBM Not Buying Sun (for Now)

There are reports that the talks related to IBM purchasing Sun have fallen apart. The New York Times reports IBM Withdraws $7 Billion Offer for Sun and the Wall Street Journal (which originally broke this story) reports IBM Talks Teeter as Sun Board Splits.

In the short term, my selfish side is pleased with this because I really enjoy using NetBeans and GlassFish and enjoy having other Sun-provided alternatives available even when I don't use them often because I am a strong believer that competition does drive better and cheaper product offerings. As I blogged on previously, I had serious doubts about the future of many of these products with IBM having more control over their future.

In the long term, however, IBM's acquiring of Sun may have been better for the general Java development world than some of the other alternatives that are now possible. IBM has committed significance resources to developing tools and resources related to Java development as evidenced by Eclipse, by WebSphere, and by developerWorks articles on Java.

It is often the case that we will never know what would have actually happened had history taken certain different turns. So the best we can do is to speculate based on past actions what might have happened. Similarly, it is difficult at this point to know if the apparent current stall in talks between IBM and Sun is beneficial or harmful to the long-term prospects of Java.

Of course, rumors of Sun being purchased by EMC, Fujitsu, HP (don't take this link too seriously!), Cisco, IBM, and Oracle have been circulated before and it is still possible that such a purchase may occur in the near future. In fact, now we are seeing rumors of even more complicated deals like Oracle and HP buying Sun and taking the pieces each wants.

No matter what happens, JavaOne will likely be dominated by talk related to any potential acquisition of Sun (or any acquisition in progress if that is the case). In fact, any uncertainty will likely weigh over the Java development community at many events for the next several months until/unless something more definitive actually happens.

Saturday, April 4, 2009

Finding the Silver Lining in the Clouds of Software Development in a Bad Economy

There are many negative consequences in the world of software development from the current poor economic conditions. Some of the most obvious negative consequences include the massive layoffs in the industry, elimination of conferences such as the SD West and Software Development Best Practices conferences, unused IT equipment, and potential reduction of investment in software services and support. In trying to find the silver lining until things improve, we can identify some positive consequences of these troubled economic times. By taking advantage of these advantages resulting from the bad economic times, we can hopefully better weather this storm.

There are some specific areas of the software development world that might actually benefit from these difficult times. For example, many believe that the bad economy is leading to increased interest in open source (such as Linux). Similarly, some also believe that these tough times will be good for lean and agile development. Others believe that Software As A Service (SaaS) business has higher 2009 projections in some estimates. Others believe that recession drives return to built-in, standards-based approaches rather than mixing of various libraries and frameworks. Still others see this leading to a new level of interest in cloud computing and mobile development.

Difficult economic times have been known to lead to increased innovation and entrepreneurism. This is often attributed to the understandable aversion to taking risks when one has a stable job that is overcome when that job is no longer available. Similarly, many people return to school or other types of training to improve their skills. Again, this is something that may have seemed too time consuming or difficult to do while working a full-time job, but seems more doable when unemployed. Furthermore, one often has more motivation to learn new things and new skills in the tougher times.

Another silver lining of unemployment can be the realization of (or remembering) the importance of networking, friends, and acquaintances. This is when sites like LinkedIn can be particularly valuable. It is best if these are kept to some degree before the period of unemployment, but it better to start late than never with the social networking. In addition, there are often many other lessons learned from unemployment as well, including greater appreciation for interesting work.

One advantage of these times is the availability of products and services at a discounted rate. An example of this is FlexBuilder being available free of charge to unemployed developers (you must accept terms including agreement that you are indeed unemployed and will use the tool only for personal use and not for production or commercial purposes). For those who have the misfortune of being unemployed, one silver lining here is the opportunity to spend time learning Flex and the availability of FlexBuilder for no cost to learn on is certainly welcome.

While FlexBuilder is now available at no charge specifically for unemployed software developers, other great tools are or have been available for no charge for the same type of use (non-commercial personal use only) and often are not limited to unemployed developers. These include most open source products (including IDEs Eclipse and NetBeans as well as application servers like GlassFish and databases such as MySQL and PostgreSQL), but also include some closed-source products and tools such as Oracle's JDeveloper IDE and Oracle Database Express Edition (XE) 10g, and SQLDeveloper.

In addition to the many blog postings with lessons learned regarding unemployment, there are many stories of people digging themselves out of unemployment, reinventing themselves or their careers, and succeeding beyond their level before the unemployment. Hopefully we'll all look back at this time in the not-too-distant future and be able to say the same about this current period whether we are currently employed or not.

Wednesday, April 1, 2009

Java: Overloading Versus Overriding

I have occasionally heard the terms method overloading and method overriding used interchangeably. While the difference between these two concepts can be relatively easily explained, the difference in the runtime resolution of these is more tricky for those new to Java.

In the code example shown next, both overloading and overriding are demonstrated. The overridden method is the toString method. The overriding in action is easy to spot with the use of @Override annotations (which are not required for overriding but are helpful in communicating to the compiler that overriding is intentional). The overloading is demonstrated by multiple print() methods accepting different classes in the Vehicle -> Automobile -> Car class hierarchy.

OverloadingExample.java


package dustin.examples;

import java.util.ArrayList;
import java.util.List;

/**
* Class demonstrating overloading/overriding issues in Java.
*/
public class OverloadingExample
{
/**
* Print out a Vehicle's toString().
*
* @param theVehicle The Vehicle whose toString() will be executed.
*/
public void print(final Vehicle theVehicle)
{
System.out.println("Vehicle: " + theVehicle);
}

/**
* Print out an Automobile's toString().
*
* @param theAutomobile The Automobile whose toString() will be executed.
*/
public void print(final Automobile theAutomobile)
{
System.out.println("Automobile: " + theAutomobile);
}

/**
* Print out a Car's toString().
*
* @param theCar The Car whose toString() will be executed.
*/
public void print(final Car theCar)
{
System.out.println("Car: " + theCar);
}

/**
* Main test to be executed.
*/
public void runTest()
{
System.out.println(
"===== COMPILE-TIME RESOLUTION IS SUFFICIENT FOR OVERLOADING =====");
print(new Vehicle());
print(new Car());
print(new Automobile());
System.out.println(
"===== COMPILE_TIME RESOLUTION NOT SUFFICIENT FOR OVERLOADING =====");
final List<Vehicle> vehicles = new ArrayList<Vehicle>();
vehicles.add(new Car());
vehicles.add(new Automobile());
vehicles.add(new Vehicle());
for (final Vehicle vehicle : vehicles)
{
print(vehicle);
}
}

/**
* Main function to run the test demonstrating Java's overloading and
* overriding.
*/
public static void main(final String[] arguments)
{
final OverloadingExample me = new OverloadingExample();
me.runTest();
}

/**
* Parent class with its own toString implementation.
*/
public static class Vehicle
{
@Override
public String toString() {return "Vehicle";}
}

/**
* Child class with its own toString implementation.
*/
public static class Automobile extends Vehicle
{
@Override
public String toString() {return "Automobile";}
}

/**
* Grandchild class with its own toString implementation.
*/
public static class Car extends Automobile
{
@Override
public String toString() {return "Car";}
}
}


When the code above is executed, the results appear as demonstrated in the screen snapshot.



As the results of this very simple example demonstrate, overloading and overriding are treated differently at runtime. The overriding always works as we would expect because the methods called are bound at runtime. The overloaded methods are bound at compile time, however, leading to results that might be somewhat unexpected.