Program Java pentru a determina clasa unui obiect

În acest exemplu, vom învăța să determinăm clasa unui obiect în Java folosind metoda getClass (), instanceof operator și metoda isInstance ().

Pentru a înțelege acest exemplu, ar trebui să aveți cunoștințele despre următoarele subiecte de programare Java:

  • Clasa și obiecte Java
  • Instanță Java a Operatorului

Exemplul 1: Verificați clasa unui obiect folosind getClass ()

 class Test1 ( // first class ) class Test2 ( // second class ) class Main ( public static void main(String() args) ( // create objects Test1 obj1 = new Test1(); Test2 obj2 = new Test2(); // get the class of the object obj1 System.out.print("The class of obj1 is: "); System.out.println(obj1.getClass()); // get the class of the object obj2 System.out.print("The class of obj2 is: "); System.out.println(obj2.getClass()); ) )

Ieșire

 Clasa obiect1 este: clasa Test1 Clasa obiect2 este: clasa Test2

În exemplul de mai sus, am folosit getClass()metoda Objectclasei pentru a obține numele clasei obiectelor obj1 și obj2.

Pentru a afla mai multe, vizitați Java Object getClass ().

Exemplul 2: Verificați clasa unui obiect folosind operatorul instanceOf

 class Test ( // class ) class Main ( public static void main(String() args) ( // create an object Test obj = new Test(); // check if obj is an object of Test if(obj instanceof Test) ( System.out.println("obj is an object of the Test class"); ) else ( System.out.println("obj is not an object of the Test class"); ) ) )

Ieșire

 obj este un obiect al clasei Test

În exemplul de mai sus, am folosit instanceofoperatorul pentru a verifica dacă obiectul obiect este o instanță a clasei Test.

Exemplul 3: Verificați clasa unui obiect folosind isInstance ()

 class Test ( // first class ) class Main ( public static void main(String() args) ( // create an object Test obj = new Test(); // check if obj is an object of Test1 if(Test.class.isInstance(obj))( System.out.println("obj is an object of the Test class"); ) else ( System.out.println("obj is not an object of the Test class"); ) ) )

Ieșire

 obj este un obiect al clasei Test

Aici, am folosit isInstance()metoda clasei Classpentru a verifica dacă obiectul obiect este un obiect al clasei Test.

isInstance()Metoda funcționează în mod similar cu instanceofoperatorul. Cu toate acestea, este preferat în timpul rulării.

Articole interesante...