Understanding of instanceof Keywords in Java

Source: Internet
Author: User

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.

Usage:
Result = Object Instanceof class
Parameters:
Result: Boolean type.
Object: Required option. An arbitrary object expression.
Class: Required option. Any of the defined object classes.
Description
If object is an instance of class, the instanceof operator returns TRUE. Returns False if object is not an instance of the specified class, or if object is null.

However, there is a difference between the instanceof in Java and the running state:

In the compilation state, the class can be the parent class of the object, its own class, and the subclass. In these three cases, Java compiles without error.

In the run-to-state, the class can be the parent class of object objects, its own class, and cannot be a subclass. In the first two cases, result is true and the last is false. But when class is a subclass, compilation does not give an error. The run result is false.

Example:

Interface person

Public interface Person {
public void eat ();
}

Implementing class people

Public class people implements person {
private int a=0;
@Override
public void Eat () {
System.out.println ("======" +a);

}

}

Sub-class Xiaoming:

Public class Xiaoming extends people {
private String name;

@Override
public void Eat () {
System.out.println ("+++++++++");
}
}

Main function

public static void Main (string[] args) {
People p=new people ();
Xiaoming x=new xiaoming ();
SYSTEM.OUT.PRINTLN (P instanceof person);
SYSTEM.OUT.PRINTLN (P instanceof xiaoming); -----2
SYSTEM.OUT.PRINTLN (x instanceof person);
SYSTEM.OUT.PRINTLN (x instanceof people);
}

Note: The code above 2 does not error at compile time.

Operation Result:

True
False
True
True

Understanding of instanceof Keywords in Java

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.