Java の共変の戻り値の型

MD Aminul Islam 2023年10月12日
  1. Covariant 戻り型を使用する利点
  2. Covariant 戻り型のデモンストレーション
Java の共変の戻り値の型

Covariant 戻り値の型という用語は、オーバーライド メソッドの戻り値の型を意味します。 型キャスト を必要とせず、オーバーライドされたメソッドの戻り値の型を絞り込むのに役立ちます。

しかし、Covariant の戻り値の型は、非プリミティブ の戻り値の型に対してのみ機能します。 この記事では、Covariant 戻り値の型について説明し、サンプル コードを使用してトピックを学習します。

Covariant 戻り型を使用する利点

始める前に、Covariant 戻り型から得られる利点を見てみましょう。 Covariant 戻り型を使用することで、以下の利点が得られます。

  1. クラス階層に存在する型キャストに関する混乱を取り除くのに役立ちます。
  2. コードを使いやすく、読みやすく、保守しやすくします。
  3. メソッドをオーバーライドするときに、より具体的な戻り値の型を取得するのに役立ちます。
  4. ClassCastException のような実行時例外を防ぎます。

Covariant 戻り型のデモンストレーション

以下のコード例では、Covariant 戻り値の型を示します。 以下の簡単な例を見てください。

class MainClass { // Declaring a main parent class
  MainClass get() { // Creating a method for the parent class
    System.out.println("A message from the main class: MainClass");
    return this;
  }
}
// Our controlling class
public class CovariantType extends MainClass { // This class inherit to the parent class
  CovariantType get() { // Overriding the parent class method
    System.out.println("A message from the main class: SubClass");
    return this;
  }
  public static void main(String[] args) {
    MainClass test = new CovariantType(); // Covariant return type. No type casting is required.
    test.get(); // Calling the method
  }
}

コードの各行の目的についてはすでに説明しました。 上記の例では、最初に親クラスでもある MainClass という名前のメイン クラスを作成し、その後、メソッド get() を宣言して定義しました。

子クラス CovariantType では、親クラス MainClass でそれを継承し、親クラスの get() メソッドをオーバーライドしました。

最後に、Covariant 型を作成し、メソッド get() を呼び出しました。 上記のコード例を実行すると、コンソールに以下の出力が表示されます。

A message from the main class: SubClass
著者: MD Aminul Islam
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

関連記事 - Java Function