Pages

Friday, October 16, 2009

Java vs Groovy: Polymorphism

While doing some studying for SCJP, I was tinkering with some stuff in the Groovy console as a way of testing some stuff in Java and I found they actually behave differently.

class Person {
  protected String name
  protected int age
  
  public Person() {
    name = "secret"
    age = -1
  }
}

class John extends Person {
  int favoriteNumber
  
  public John() {
    name = "nobody special"
    age = 0
    favoriteNumber = 7
  }
  
  public String doNothing() {
    return "junk"
  }
}

Person p = new John()
println p.doNothing()

If you do this in Java (splitting the classes out to their own files of course), it won't compile. Java looks at the reference type for available methods, so you will get a NoSuchMethodException. In Groovy, however, it looks at the type of the object, not the type of the reference so the method is found at runtime. And this is probably what you would want, so I can refer to John or Mary as a generic Person, but they still do the things they do in a John or Mary way.

No comments:

Post a Comment