[chuck-users] Casting behaviour

Michael Heuer heuermh at gmail.com
Fri Oct 17 10:40:26 EDT 2014


Gonzalo wrote:
> I have this (unexpected?) behaviour when casting. I can cast a object to its
> parent class, but the methods that get executed are still their own (and
> viceversa). I.e.:
>
> ----------------------------------
> public class Parent {
>   fun void test() {
>     <<< "Parent" >>>;
>   }
> }
>
> class Child extends Parent {
>   fun void test() {
>     <<< "Child" >>>;
>   }
> }
>
> Parent p;
> Child @ ch;
> p $ Child @=> ch;
> ch.test(); // prints Parent

This shouldn't work, because p !instanceof Child, the cast should be a
compiler error.


> Child ch2;
> ch2 $ Parent @=> p;
> p.test(); // prints Child

This should be expected, because Child.test() overrides Parent.test().


> Is this intended behavior? What's the point of casting then?

I typically only use casting when pulling object references out of
data structures that hold arrays of Object references, e.g. an
ArrayList

https://github.com/heuermh/lick/blob/master/Freeze.ck#L73


> I might describe too what I'm trying to do, maybe there's a better approach.
> I have a .create method in Parent that returns a Parent object, and I wanted
> to create that same method in Child, but I can't do it because the arguments
> are the same, and it won't let me overwrite the method when only the return
> type changes. So to create a child with the .create method, I do this:
>
> Parent.create(...) $ Child @=> Child ch;
>
> Which works, but then it still behaves as a parent, so it defeats the whole
> purpose.

Having proper constructors in ChucK would help here

https://github.com/spencersalazar/chuck/issues/32


A workaround might be to include the classname in your create methods

class Parent {
  fun static Parent createParent(...) { }
}

class Child extends Parent {
  fun static Child createChild(...) { }
}

   michael


More information about the chuck-users mailing list