The difference analysis of instanceof and GetClass () in Java _java

Source: Internet
Author: User

Class A {}

Class B extends A {}

Object O1 = new A ();
Object O2 = new B ();

O1 instanceof A => True
O1 instanceof B => false
O2 instanceof A => true//<================ here
O2 instanceof B => True

O1.getclass (). Equals (A.class) => true
O1.getclass (). Equals (B.class) => false
O2.getclass (). Equals (A.class) => false//<===============here
O2.getclass (). Equals (B.class) => true


GetClass () would be useful if you are want to make sure your instance are not a subclass of the class for you are comparing with.

A very perfect method of equals:

Copy Code code as follows:

public boolean equals (Object otherobject)
{
A quick test to the if the objects are identical
if (this = = Otherobject) return true;

Must return FALSE if the explicit parameter is NULL
if (Otherobject = null) return false;

If the classes don ' t match, they can ' t be equal
if (GetClass ()!= Otherobject.getclass ()) return false;

Now we know Otherobject is a non-null Employee
Employee other = (employee) Otherobject;

Test whether the fields have identical values
Return Name.equals (other.name) && salary = = Other.salary && hireday.equals (other.hireday);
}

Related Article

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.