V tem primeru se bomo naučili določiti razred predmeta v Javi z uporabo metode getClass (), instanceof in metode isInstance ().
Če želite razumeti ta primer, morate poznati naslednje programske teme Java:
- Razred Java in predmeti
- Primerek Java operaterja
Primer 1: Preverite razred predmeta s pomočjo 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()); ) )
Izhod
Razred obj1 je: razred Test1 Razred obj2 je: razred Test2
V zgornjem primeru smo uporabili getClass()metodo Objectrazreda, da smo dobili ime razreda predmetov obj1 in obj2.
Če želite izvedeti več, obiščite Java Object getClass ().
Primer 2: Preverite razred predmeta z uporabo operatorja 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"); ) ) )
Izhod
obj je predmet razreda Test
V zgornjem primeru smo z instanceofoperatorjem preverili, ali je objekt obj primerek razreda Test.
Primer 3: Preverite razred predmeta s pomočjo 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"); ) ) )
Izhod
obj je predmet razreda Test
Tu smo uporabili isInstance()metodo razreda, Classda preverimo, ali je objekt obj objekt razreda Test.
isInstance()Metoda deluje podobno kot instanceofoperaterja. Vendar je prednost med izvajanjem.








