Method overloading in groovy

Posted by slojo on Stack Overflow See other posts from Stack Overflow or by slojo
Published on 2010-05-22T16:51:40Z Indexed on 2010/05/22 17:00 UTC
Read the original article Hit count: 182

Filed under:
|

I am trying to take advantage of the convenience of groovy's scripting syntax to assign properties, but having trouble with a specific case. I must be missing something simple here. I define class A, B, C as so:

class A {

    A() {
        println "Constructed class A!"
    }

}

class B {

    B() {
        println "Constructed class B!"
    }

}

class C {

    private member 

    C() {
        println "Constructed class C!"
    }

    def setMember(A a) {

        println "Called setMember(A)!"
        member = a

    }

    def setMember(B b) {

        println "Called setMember(B)!"
        member = b

    }

}

And then try the following calls in a script:

c = new C()

c.setMember(new A()) // works
c.member = new A()   // works

c.setMember(new B()) // works
c.member = new B()   // doesn't work!

The last assignment results in an error: 'Cannot cast object of class B to class A". Why doesn't it call the proper setMember method for class B like it does for class A?

© Stack Overflow or respective owner

Related posts about groovy

Related posts about method-overloading