Understanding of instanceof Keywords in Java

Source: Internet
Author: User

Concept: 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.

Formula: Result = Object instanceof class

Parametric analysis:

Result: Boolean type

Object: An arbitrary instance or an expression

Class: Any one of the defined classes

Results Analysis:

Returns true if object is an instance of class, or false if not or if object is null

Instaanceof are different at run time and compile time:

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.

public class Base {
String name = "Base";
public void Basea () {
System.out.println ("name is" + name);
}
}

public class Child extends Base {
String name = "Child";
String age = "18";
}

public class Test {

public static void Main (string[] args) {
Base base = new Child ();
System.out.print (base instanceof Base);
System.out.print (base instanceof Child);
System.out.print (base instanceof Object);
System.out.print (base instanceof System); --Compilation errors

}

}

 

Understanding of instanceof Keywords 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.