Casting


I alluded to the fact that a subclass is a member of the parent class, but the parent class is not a member of the subclass. This makes perfect sense, but it can at times make for some confusion, especially when dealing with overridden and overloaded methods.

I want to return to the Alpha and Beta classes from the previous examples and add a method to each one; this will illustrate the potential confusion (at least, it was confusing to me).

Alpha will add the following:

Sub TestMethod(a as Alpha)


Beta will add the following:

Sub TestMethod(b as Beta)


First, take a look at the following example:

Dim a as Alpha Dim b as Beta Dim s as String a = New Beta("What's this?") 


What is a? Is it an Alpha or a Beta? One way to tell would be to invoke the getName() method and see what is returned. If you recall, I overloaded the getName() method so that it accepted a string as a parameter.

s = a.getName("My String") // Error! 


If you try to call the Beta method you'll get an error. That's because as far as REALbasic is concerned, a represents an Alpha. However, because you instantiated it as a Beta, you do have access to Beta's methods. You can do this by casting the a as a Beta.

s = Beta(a).getName("My String") // s equals "My String" 


Reference the class to which you are casting the object, followed by the object surrounded in parentheses, and now you will get access to the methods of Beta.

Note that the following will not work:

Dim a as Alpha Dim b as Beta Dim s as String a = New Alpha("What's this?") s = Beta(a).getName("A String") // Error 


The reason is that a is an Alpha, not a Beta. Recall that the superclass is not a member of the subclass.

Dim a as Alpha Dim bool as Boolean a = New Alpha("What's this?") bool = (a Isa Beta) // bool is False 





REALbasic Cross-Platform Application Development
REALbasic Cross-Platform Application Development
ISBN: 0672328135
EAN: 2147483647
Year: 2004
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net