The role of instanceof and GetClass () in Java

Source: Internet
Author: User

Beginners are inevitably a little confused about the role of Java instanceof and GetClass (), the following one by one to explain.

Parent Class A:

class A {}
Sub-Class B:
class extends
Constructing objects
New
New
First, instanceof
Demo One:
instanceof
instanceof
instanceof
instanceof

Analysis ==>

Usage:
English: Result = Object instanceof class

English: result = An Instance object instanceof a class name

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.

Summary: S (object) instanceof T (Class) simply, instanceof is to determine whether the object S is an instance of the T class, or a subclass instance of the T class. Second, GetClass
Demo Two:
1, O1.getclass (). Equals (A.class
2, O1.getclass (). Equals (B.class
3, O2.getclass (). Equals (A.class
4, O2.getclass (). Equals (B.class
The analysis ==>getclass method is defined in JDK1.8 as follows:
/**
* Returns the runtime class of this Object
*/
Public Final native Class<?> getclass ();

Function: Returns the object at the run-time class. GetClass () would be useful if you want to make sure your instance was not a subclass of the class you were comparing with. Three, the difference between instanceof and GetClass 1, the role:
    • Instanceof: Used primarily to determine the relationship between objects and classes.
    • GetClass: Primarily used to determine the relationship between classes and classes.
Reference: 1, http://www.jb51.net/article/36114.htm

The role of 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.