Home > Articles

Classes and Objects

  • Print
  • + Share This
This chapter is from the book


Overloading and overriding are two words that look alike, sound alike, and refer to similar things with markedly different behavior. That's a recipe for confusion if ever there was one. When you are creating classes and subclassing them, you will be making use of both overloading and overriding.

Overloading is associated with the idea of Polymorphism (who comes up with these words?). All that Polymorphism means is that you can have multiple versions of the same method that are distinguished according to the parameters that are passed to them.

Note that REALbasic does not pay any attention to the return value offered by a method when overloading methods. This means you can't do something like this:

Function myFunction(aString as String) as Integer
Function myFunction(aString as String) as String

and expect to be able to do this:

Dim i as Integer
Dim s as String
i = myFunction("Hello")
s = myFunction("Hello")

The only thing that counts are the arguments.

Now, when I instantiate the Alpha or Beta classes, I pass a string to the Constructor, and this is the value that the getName() method returns. Let's say for the moment that there are times when I want getName() to return a different value. One way to do it is to change the value of the property, but because that property is Private, it requires some extra steps, so we'll hold off on that approach for now.

Another way to do it would be to overload the getName() method, which means implementing another version of getName() with a different signature. Remember, a method signature refers to the collection of parameters that it takes. Because the original getName() doesn't take any parameters, we will implement a new version of getName() that takes a string as a parameter. For this example, implement the new method in Beta.

Function getName(aNewName as String) as String
   Return aNewName
End Function

Now let's see this overloaded method in practice.

Dim a as Alpha
Dim b as Beta
Dim s,t, u as String
a = New Alpha("Good morning.")
b = New Beta("Good night.")
s = b.getName() // s = "Good night."
t = b.getName("Hello.") // t = "Hello."
u = a.getName("Goodbye.") // Error!
// Won't compile because Alpha doesn't implement this method.

As you can see, REALbasic knows which version of getName() to call for the Beta class based solely on the parameters passed. In the first example, because nothing is passed, it returns the value of the property Name. When a string is passed, it returns the value of the string. Out of curiosity, I tried to pass a string to the Alpha implementation of getName(), and the compiler fell into all kinds of histrionics because Alpha doesn't implement a method called getName() that expects a string as a parameter. Remember, Beta is a subclass of Alpha. Alpha's methods are available to Beta, but Beta's aren't available to Alpha.

  • + Share This
  • 🔖 Save To Your Account