10 Ağustos 2020 Pazartesi

Covariant Return Type - Covariance

Giriş
Açıklaması şöyle
Covariant method overriding was introduced in Java 5, but it seems it lost between other more powerful features of that release.
...
Covariant method overriding helps to remove type casting on client side, by allowing you to return subtype of actually return type of overridden method.
Örnek
Java 5'ten sonra covariant return type desteklendiği için Object dönmeden şöyle de yapabilirim. Metodumuz CloneNotSupportedException fırlattmaz.
public MyObject implements Cloneable {
  @Override
  public MyObject clone() {
    try {
      return (MyObject)super.clone();
    } catch (CloneNotSupportedException e) {
      throw new AssertionError();
    }
  }
}

Hiç yorum yok:

Yorum Gönder