Over a million developers have joined DZone.

Covariant Return Types In Java 5

·
Surprisingly legal code under Java 5, using covariant return types.


public class CovarientReturn {

  static class A {
    public Number getNumber() {
      System.out.println("Number");
      return new Integer(1);
    }
  }

  static class B extends A {
    public Integer getNumber() {
      System.out.println("Integer");
      return new Integer(1);
    }
  }

  public static void main(String[] args) {
    A a = new A();
    B b = new B();

    Number n = a.getNumber();
    Integer i = b.getNumber();
  }

}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}