Difference between instanceof and getClass () in java

Source: Internet
Author: User

Class {}

Class B extends {}

Object o1 = new ();
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 () will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing.

A perfect way to write the equals method:

Copy codeThe Code is as follows: public boolean equals (Object otherObject)
{
// A quick test to see 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 );
}

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.