Friday, October 16, 2009

Java vs Groovy: Overriding static methods

The Java equivalent of below will not compile, but in Groovy it works fine. Groovy supports overriding static methods, whereas Java does not.

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

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

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

I don't think this would be a problem. You might want each inherited class to have its own (maybe static) version of a method, but for every instance of the class to only have one in memory. If you don't want the children overriding the method, you should just make them final.