Monday 19 September 2011

Java: Method Names, Scope

    So we know a typical java program will end up making use of multiple classes, some being programmer-created, and a bunch being used from the JDK library. Some thought needs to be put into how the method names are used in all these classes and how they coexist.
    (Aside: I just spent the last half hour typing out the completely wrong thing.)
    We know from before that, as long as variables are declared in separate scopes (such as 2 different methods), they can have the same name. Well, the same general principle applies to methods themselves, which works fine as long as the methods are actually in different scopes. GenericStack.pop() and IntStack.pop() for instance, differentiate between the 2 methods based on which object is calling it, even though in this case, there's not a difference.

Overloading Methods:
    It turns out that methods are not identified by their name alone, so we don't strictly need to have different names for every method inside a specific scope. Surprise! A method's identifier is a combination of the method's name as well as the amount and type of parameters it takes. This opens the way for having a few methods that differ oh-so-slightly within the same scope. This nifty little trick is known as overloading. Overloaded methods don't take into account return values, so different value types can be used with them. Overloading is pretty serious business with respect to object oriented programming, since it allows us to have different implementations of a method depending on the amount and values of parameters provided. Think of several add methods to a stack of unspecified type.


    That's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!


    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 

2 comments:

  1. I've never heard of overloading in any of my classes before so this is new for me.

    (Also, she loves The Lonely Island so yes, I would consider that as a gift for her :P)

    ReplyDelete
  2. Yay, I'm like, a real teacher or something!

    ReplyDelete