Analysis of differences between instanceof and GetClass () in Java

Source: Internet
Author: User

This article describes the differential analysis of instanceof and GetClass () in Java. Need a friend to reference under

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 want to make sure your instance was not a subclass of the class you were comparing with.

A very perfect method of equals notation:

Copy CodeThe code is as follows:


public boolean equals (Object otherobject)
{
A quick test to see if the objects is 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 has identical values
Return Name.equals (other.name) && salary = = Other.salary && hireday.equals (other.hireday);
}

Analysis of differences between instanceof and GetClass () in Java

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.