Java でオブジェクトがクラスのインスタンスであるかどうかを確認する方法

JavaJavaBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Java で instanceof キーワードを使用して、オブジェクトが特定のクラスまたはインターフェースのインスタンスであるかどうかをチェックする方法を学びます。基本的な使い方を探索し、サブクラスでの動作をテストし、null オブジェクトの扱いを理解します。

実践的な例を通じて、オブジェクト指向プログラミングの基本概念である実行時型チェックを行うために instanceof を使用する実践的な経験を積むことができます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["Object-Oriented and Advanced Concepts"]) java/BasicSyntaxGroup -.-> java/if_else("If...Else") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("Classes/Objects") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("OOP") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inheritance("Inheritance") subgraph Lab Skills java/if_else -.-> lab-560010{{"Java でオブジェクトがクラスのインスタンスであるかどうかを確認する方法"}} java/classes_objects -.-> lab-560010{{"Java でオブジェクトがクラスのインスタンスであるかどうかを確認する方法"}} java/oop -.-> lab-560010{{"Java でオブジェクトがクラスのインスタンスであるかどうかを確認する方法"}} java/inheritance -.-> lab-560010{{"Java でオブジェクトがクラスのインスタンスであるかどうかを確認する方法"}} end

クラスチェックに instanceof を使用する

このステップでは、Java の instanceof キーワードを探索します。instanceof キーワードは、オブジェクトが特定のクラスのインスタンスであるか、または特定のインターフェースを実装しているかをテストするために使用されます。これは、実行時にオブジェクトの型をチェックするための便利なツールです。

instanceof がどのように機能するかを示すために、簡単な Java プログラムを作成しましょう。

  1. WebIDE を開き、~/project ディレクトリにいることを確認します。ターミナルのプロンプトを見るか、pwd と入力して Enter キーを押すことで確認できます。

  2. ~/project ディレクトリに TypeCheck.java という名前の新しい Java ファイルを作成します。左側のファイルエクスプローラーで右クリックして「New File」を選択し、TypeCheck.java と入力することで作成できます。

  3. エディタで TypeCheck.java ファイルを開き、以下のコードを貼り付けます。

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
        }
    }

    このコードでは、以下のことを行っています。

    • 基底クラス Animal と 2 つのサブクラス DogCat を定義しています。
    • main メソッドでは、Animal 型の変数 myAnimal を作成し、Dog オブジェクトを代入しています。これは、DogAnimal の一種であるため可能です。
    • その後、instanceof キーワードを使用して、myAnimalDogCatAnimal のインスタンスであるかどうかをチェックしています。
  4. TypeCheck.java ファイルを保存します(Ctrl+S または Cmd+S)。

  5. WebIDE の下部にあるターミナルを開き、以下のコマンドを実行して Java プログラムをコンパイルします。

    javac TypeCheck.java

    エラーがなければ、このコマンドにより ~/project ディレクトリに TypeCheck.classAnimal.classDog.classCat.class ファイルが作成されます。

  6. 以下のコマンドを使用してコンパイルされたプログラムを実行します。

    java TypeCheck

    以下のような出力が表示されるはずです。

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal

    この出力は、Dog オブジェクトを保持する myAnimal が実際に Dog のインスタンスであり、そのスーパークラス Animal のインスタンスでもあるが、Cat のインスタンスではないことを確認しています。

あなたは、Java で instanceof キーワードを使用してオブジェクトの型をチェックすることに成功しました。次のステップでは、instanceof がサブクラスとどのように動作するかを探索します。

サブクラスでのテスト

前のステップで、オブジェクトは自身のクラスのインスタンスであると同時に、そのスーパークラスのインスタンスでもあると見なされることを確認しました。ここでは、instanceof が異なるオブジェクト型とそのサブクラスでどのように動作するかをさらに探索します。

既存の TypeCheck.java ファイルを修正して、Cat オブジェクトで instanceof をテストします。

  1. WebIDE のエディタで TypeCheck.java ファイルを開きます。

  2. main メソッドを見つけ、既存の myAnimal のチェックの後に以下のコード行を追加します。

            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }

    これで、完全な TypeCheck.java ファイルは以下のようになります。

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is not an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is not an instance of Animal");
            }
        }
    }
  3. 修正した TypeCheck.java ファイルを保存します。

  4. ターミナルでプログラムを再度コンパイルします。

    javac TypeCheck.java
  5. コンパイルしたプログラムを実行します。

    java TypeCheck

    これで、以下のような出力が表示されるはずです。

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal

    この出力は、Cat オブジェクトを保持する anotherAnimalCatAnimal のインスタンスであるが、Dog のインスタンスではないことを示しています。これにより、instanceof がオブジェクトの実際の型とその継承階層をチェックするという概念が強化されます。

あなたは、異なるサブクラスのオブジェクトで instanceof キーワードを正常にテストしました。次のステップでは、instanceofnull オブジェクトでどのように動作するかを見ていきます。

null オブジェクトでの検証

この最後のステップでは、テスト対象のオブジェクトが null の場合に instanceof キーワードがどのように動作するかを調査します。これを理解することは、Java プログラムで潜在的なエラーを回避するために重要です。

再度 TypeCheck.java ファイルを修正して、null オブジェクトでのテストを追加します。

  1. WebIDE のエディタで TypeCheck.java ファイルを開きます。

  2. main メソッドの末尾、前のテストの後に以下のコード行を追加します。

            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }

    これで、完全な TypeCheck.java ファイルは以下のようになります。

    class Animal {
        // Base class
    }
    
    class Dog extends Animal {
        // Subclass of Animal
    }
    
    class Cat extends Animal {
        // Subclass of Animal
    }
    
    public class TypeCheck {
        public static void main(String[] args) {
            Animal myAnimal = new Dog();
    
            // Check if myAnimal is an instance of Dog
            if (myAnimal instanceof Dog) {
                System.out.println("myAnimal is an instance of Dog");
            } else {
                System.out.println("myAnimal is not an instance of Dog");
            }
    
            // Check if myAnimal is an instance of Cat
            if (myAnimal instanceof Cat) {
                System.out.println("myAnimal is not an instance of Cat");
            } else {
                System.out.println("myAnimal is not an instance of Cat");
            }
    
            // Check if myAnimal is an instance of Animal
            if (myAnimal instanceof Animal) {
                System.out.println("myAnimal is an instance of Animal");
            } else {
                System.out.println("myAnimal is not an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a Cat object ---");
            Animal anotherAnimal = new Cat();
    
            // Check if anotherAnimal is an instance of Dog
            if (anotherAnimal instanceof Dog) {
                System.out.println("anotherAnimal is not an instance of Dog");
            } else {
                System.out.println("anotherAnimal is not an instance of Dog");
            }
    
            // Check if anotherAnimal is an instance of Cat
            if (anotherAnimal instanceof Cat) {
                System.out.println("anotherAnimal is an instance of Cat");
            } else {
                System.out.println("anotherAnimal is an instance of Cat");
            }
    
            // Check if anotherAnimal is an instance of Animal
            if (anotherAnimal instanceof Animal) {
                System.out.println("anotherAnimal is an instance of Animal");
            } else {
                System.out.println("anotherAnimal is an instance of Animal");
            }
    
            System.out.println("\n--- Testing with a null object ---");
            Animal nullAnimal = null;
    
            // Check if nullAnimal is an instance of Dog
            if (nullAnimal instanceof Dog) {
                System.out.println("nullAnimal is an instance of Dog");
            } else {
                System.out.println("nullAnimal is not an instance of Dog");
            }
    
            // Check if nullAnimal is an instance of Animal
            if (nullAnimal instanceof Animal) {
                System.out.println("nullAnimal is an instance of Animal");
            } else {
                System.out.println("nullAnimal is not an instance of Animal");
            }
        }
    }
  3. 修正した TypeCheck.java ファイルを保存します。

  4. ターミナルでプログラムをコンパイルします。

    javac TypeCheck.java
  5. コンパイルしたプログラムを実行します。

    java TypeCheck

    以下のような出力が表示されるはずです。

    myAnimal is an instance of Dog
    myAnimal is not an instance of Cat
    myAnimal is an instance of Animal
    
    --- Testing with a Cat object ---
    anotherAnimal is not an instance of Dog
    anotherAnimal is an instance of Cat
    anotherAnimal is an instance of Animal
    
    --- Testing with a null object ---
    nullAnimal is not an instance of Dog
    nullAnimal is not an instance of Animal

    出力からわかるように、instanceof でテストするオブジェクトが null の場合、結果は常に false になります。これは、予期しない動作や NullPointerException を回避するために instanceof を使用する際に覚えておく重要なポイントです。

あなたは、instanceof キーワードが null オブジェクトでどのように動作するかを正常に検証しました。これで instanceof キーワードの探索は終了です。

まとめ

この実験では、Java の instanceof キーワードを使用して、オブジェクトが特定のクラスのインスタンスであるか、または特定のインターフェースを実装しているかをチェックする方法を学びました。基底クラスとサブクラスを持つ簡単なプログラムを作成し、instanceof を使用して実行時にオブジェクトの型を検証することで、その使い方を実証しました。

さらに、instanceof がサブクラスでどのように動作するかを調べ、オブジェクトは自身のクラスのインスタンスであると同時に、すべてのスーパークラスのインスタンスと見なされることを確認しました。最後に、instanceof を null オブジェクトに適用した場合の動作を調べ、このような場合には常に false を返すことを理解しました。