Table of Contents
How instanceOf work?
Examples of instanceOf in Java
Rules for instanceOf Operator
Conclusion
Home Java javaTutorial instanceOf in Java

instanceOf in Java

Aug 30, 2024 pm 03:44 PM
java

InstanceOf in Java is used for determining the relationship of an object with its class when the inheritance concept is implemented in the Java code snippet. The instanceOf class, in general, is applicable for the object-oriented  programming languages that allow the inheritance, and it returns the output values in the form of boolean results, that is, either true or false. If the instanceOf class variable has a NULL value, then the class returns the output as ‘false’. As this class is used for comparison purposes, it is also called as ‘type comparison operator’.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

The instanceOf class is used to check if the object is of any class or not.

obj instanceOf object
Copy after login

Above is the standard syntax for instanceOf class. Here, the obj is the name of the object that must have been created earlier (reference). instanceOf is the keyword, and the object is the class or the interface with which we match the obj object.

In various cases, instanceOf can be proved to be of major use, like where we have a collection of objects, and you are not sure of which object it refers to. An example of such a case can be a simple form with many controls.

Also, if in case we use instanceOf with a variable that has a NULL value, it is sure to return false.

How instanceOf work?

The instanceOf operator in java works on a simple is-a relationship. Simply stating, is-a relationship is an object-oriented concept, where we compare or, say, work on a relation among abstractions, where class A is a subclass of class B. This is a relationship totally based on inheritance. In other words, it is like saying, “X is of Y type”.

Now, let’s understand the working of instanceOf, along with the respective code.

First, we’ll create a class named Parent.

Code:

class Parent{
}
//Then let’s add a simple main class.
public static void main(String args[]) {
}
Copy after login

We’ll then create an instance of our Parent class.

Parent child = new Parent();
Copy after login

Finally, we’ll use the instanceOf operator to check the relationship between child and Parent. Which goes like this: child instanceOf Parent

Now, as mentioned earlier, the syntax for instanceOf goes from an object that has to check, then the instanceOf keyword and then the class/interface with which the given object is to be tested.

At any point where we encounter with the keyword “extends” or “implements” in a class declaration, it’s a clear sign of is-a relationship being used.

Examples of instanceOf in Java

The following example demonstrates a single line use of instanceOf.

class instanceof_java{
public static void main(String args[]) {
instanceof_java s = new instanceof_java();
System.out.println(s instanceOf instanceof_java);
}
}
Copy after login

Code Interpretation: Started with creating a simple class instanceof_java. In the class instanceof_java, we have our main class, and within our main class, we have an object s created. This object s is of instanceof_java type. Then to implement the working of instanceOf, we provided an output statement with object s. In the last line, we passed s along with the instanceof keyword and the parent class. Upon execution, the code will return ‘true’ because the object s is of instanceof type.

instanceOf in Java

Moving further, if we have an object of our known class or interface but have not assigned any value to the same object, it is bound to return false, even though we are of the same class.

class instanceof_sample{
public static void main(String args[]) {
instanceof_sample new = null;
System.out.println(new instanceOf instanceof_sample);
}
}
Copy after login

Here we have a similar code as we had for the earlier example, but with a null value object. When executed, this code will return false. As we can see, object new is the instance of instanceof_sample, but new is being assigned with a null value, which returns in false.

instanceOf in Java

Rules for instanceOf Operator

Based on whether the object ref is not null and an instance of the referred type. When X is the simple class of the object referred, and Y is the resolved class or an array of an interface type.

  • When X is a simple class, then:
  • If Y is a class type, then the X must be a subclass of Y, or X must the same class as Y.
  • If Y is an interface type, then the X class must implement interface T.
  • When X is type interface, then:
  • If Y is a class type, then the Y must be an Object.
  • Y can be the same as the interface as X or super interface of X if Y is an interface type.
  • If X is a class, which is representing the array type SC[], which is an array of type SC components, then:
  • If Y is a class type, then Y must be an object.
  • If Y is an interface type, then Y must be of interface type implemented by arrays.

Finally, we will demonstrate an instanceOf program to understand that the parent object cannot be an instance of the child class.

Program

class Subject {  }
class Topic extends Subject { }
class instanceof_java
{
public static void main(String[] args)
{
Subject history = new Subject ();
if (history instanceof Topic)
System.out.println("history is instance of Topic");
else
System.out.println("history is NOT instance of Topic");
}
}
Copy after login

Code Interpretation: For the purpose of understanding the instanceOf operator in different scenarios, we wrote the above code. We created a simple class Subject and then another class Topic, which extends class Subject, making the class Topic as child and class Subject as Parent here. Then another class with the main method. Within the main method, we created a new instance of parent class Subject. In the IF ELSE loop, we checked the instance object’s condition with the parent class Subject. If the condition was fulfilled, it would return “history is an instance of Topic” and “history is NOT an instance of Topic” if the condition fails.

Upon executing the above code, the output will be “history is NOT an instance of Topic”, meaning the condition passed in IF fails. It happened because we tried to check the parent of the object “history” with the class Topic. We know that the class Topic extends the class Subject, meaning Topic is a subclass to Subject. And when we tried to check the type of history with class Topic, it returns false (NOT). This means the Parent Object cannot be an instance of a class.

 Output:

instanceOf in Java

Conclusion

We have learned about instanceOf class in Java, which simply decides if the object is of the given type. We understood how is-a relationship impacts on instanceOf operator. Also known as a comparison operator, instanceOf is based on inheritance.

The above is the detailed content of instanceOf in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles