This article is a mirror article of machine translation, please click here to jump to the original article.

View: 9147|Reply: 0

[Communication] Understanding of the instanceof keyword in Java

[Copy link]
Posted on 9/5/2018 4:34:49 PM | | |
The instanceof operator in Java is used to indicate at runtime whether an object is an instance of a particular class. instanceof indicates whether the object is an instance of this particular class or its subclass by returning a boolean.

instanceof in Java is is in .net!

Usage:
result = object instanceof class
Parameter:
Result: Boolean type.
Object: Required. Arbitrary object expressions.
Class: Required. Any defined object class.
Illustrate:
If the object is an instance of the class, the instanceof operator returns true. If the object is not an instance of the specified class, or if the object is null, false is returned.

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

In the compiled state, class can be the parent class, its own class, or child class of the object object. In these three cases, Java does not report an error when compiling.

In the running transition, class can be the parent class of the object object, its own class, not a child class. In the first two cases, the result is true, and the last one is false. However, when class is a subclass, the compilation will not report an error. The run result is false.

Example:

interface Person

public interface Person {
public void eat();
}

Implement the People class

public class People implements Person {
private int a=0;
@Override
public void eat() {
  System.out.println("======"+a);

}

}

Subcategory xiaoming:

public class xiaoming extends People {
private String name;

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

main function



Note: The code in the above 2 places will not report an error when compiling.

Run result:

true
false
true
true







Previous:Spring Boot uses profiles to configure profiles for different environments
Next:SQL Server jobs
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com