The instanceof operator in Java is used to indicate at run time whether an object is an instance of a particular class. Instanceof Indicates whether this object is an instance of this particular class or its subclasses by returning a Boolean value.
Usage:
Result = Object Instanceof class
Parameters:
Result: Boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description
If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.
PackageFirst ;//: Initialization/passingthis.java//This keyword is also useful for passing the current object to another methodclassPerson {//Public void Eat (Apple apple) {//Apple peeled = apple.getpeeled ();//System.out.println ("Yummy");// }Apple Apple; Orange Orange; Public voideat (Object object) {
The //instanceof method works the same way as the following Object.getclass (). GetName (). //if (object instanceof Apple) {System.out.println (Object.getclass (). GetName ()); if(Object.getclass (). GetName (). Equals ("First". Apple ") ) {Apple=((Apple) object). getpeeled (); System.out.println ("I want the Little Apple:" +Apple); } Else if(ObjectinstanceofOrange) {Orange=((Orange) object). getpeeled (); System.out.println ("I want the Little oranges:" +Orange); } Else{System.out.println ("O.m.g,i has nothing!"); } }}/** is an external tool method that will perform operations that must be placed outside Apple for some reason. (Perhaps because the external method is applied to many different classes * and you don't want to repeat the code.) For example, I can expand people not only to eat apples but also to eat oranges. We can plant an orange first. */classPeeler {StaticApple Peel (Apple apple) {System.out.println ("Plant a little apple:" +Apple); //.. remove Peel returnApple//Peeled } StaticOrange peel (orange orange) {System.out.println ("Plant a small orange:" +Orange); returnOrange; }}classApple {Apple getpeeled () {returnPeeler.peel ( This); }}classOrange {Orange getpeeled () {returnPeeler.peel ( This); }} Public classPassingthis { Public Static voidMain (string[] args) {NewPerson (). Eat (NewApple ()); NewPerson (). Eat (NewOrange ()); }}
The use of the Java instanceof method