How to Use instanceof

Source: Internet
Author: User

How to Use instanceof

Instanceof is a simple method. Is to judge whether the left is a subclass on the right ..

Package Connection; class monkey {} class longarmMonkey extends monkey {} class Engineer extends longarmMonkey {} class engineerSon extends Engineer {} public class Instanceof {public static void main (String [] args) {// who am woIam (new engineerSon ();} private static void woIam (Object obj) {if (obj instanceof Object) {System. out. println ("My ancestor");} if (obj instanceof monkey) {System. out. println ("I am a monkey");} if (obj instanceof longarmMonkey) {System. out. println ("I am a great ape");} if (obj instanceof Engineer) {System. out. println ("I Am a programmer");} if (obj instanceof engineerSon) {System. out. println ("I'm a mini programmer ");}}}

That's why. If the instantiated object referenced on the left of instanceof is a subclass of the right class, true is returned ..

So no matter how many generations you are, Xuan sun, as long as you have the lineage of your ancestors, you are my descendants.

Public boolean equals (Object anObject) {// It is to compare whether it is the same reference and whether it all points to the case in the same memory if (this = anObject) {return true ;} // instanceof is used here to determine whether the imported data is of the String type. // here, it is noted that although the imported data is of the object type, it can only be of the String or String type. the parent class can be true if (anObject instanceof String) {String anotherString = (String) anObject; // converts int n to value. length; if (n = anotherString. value. length) {// determine whether the length is consistent to accelerate the determination of char v1 [] = valu E; char v2 [] = anotherString. value; int I = 0; while (n --! = 0) {if (v1 [I]! = V2 [I]) return false; I ++;} // This algorithm is very good .. Returns true;} return false ;}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.