V tomto príklade sa naučíme určovať triedu objektu v Jave pomocou metódy getClass (), operátora instanceof a metódy isInstance ().
Aby ste pochopili tento príklad, mali by ste mať znalosti nasledujúcich tém programovania v jazyku Java:
- Trieda Java a objekty
- Operátor Java instanceof
Príklad 1: Skontrolujte triedu objektu pomocou funkcie 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()); ) )
Výkon
Trieda obj1 je: trieda Test1 Trieda obj2 je: trieda Test2
Vo vyššie uvedenom príklade sme použili getClass()
metódu Object
triedy na získanie názvu triedy objektov obj1 a obj2.
Ak sa chcete dozvedieť viac, navštívte Java Object getClass ().
Príklad 2: Skontrolujte triedu objektu pomocou operátora 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"); ) ) )
Výkon
obj je objektom triedy Test
Vo vyššie uvedenom príklade sme pomocou instanceof
operátora skontrolovali, či je objekt obj inštanciou triedy Test.
Príklad 3: Skontrolujte triedu objektu pomocou 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"); ) ) )
Výkon
obj je objektom triedy Test
Tu sme použili isInstance()
metódu triedy Class
na kontrolu, či je objekt obj objektom triedy Test.
isInstance()
Metóda funguje podobne ako instanceof
operátor. Je však preferované počas doby behu.