The operator that was born to be born, instanceof (Java) ~ How to use the instanceof operator ~

Note

Details of the class used

This article is a continuation of "I wrote about downcast in an easy-to-understand manner". Therefore, some source code (Cat class, Dog class, Life_form class) etc. is posted in the "Details of the class used for explanation" item at the bottom.

The text starts with "What is the instance of operator?".

About upcast and downcast

This article gives a quick review of upcasts and downcasts, but more. If you want to know more, please see the following article. -"Upcast (Java) that can reduce the amount of change when specifications are changed" -"I wrote about Java downcast in an easy-to-understand manner"

Development environment

Text editor used Atom (hereinafter atom -vertion execution result)

Atom : 1.28.0 Electron: 2.0.3 Chrome : 61.0.3163.100 Node : 8.9.3

~ Below, the execution result of the command "java -version" ~

java version "1.8.0_161" Java(TM) SE Runtime Environment (build 1.8.0_161-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)

Upcast and downcast

A light review before going into the instanceof description

The instanceof operator is also closely related to upcast and downcast. Therefore, let's review a little.

Upcasting is the initialization of a parent class instance with a child class instance. This means that even if you haven't decided how many child classes will be created at the design stage, you can pass any child class instance by making the argument a parent class instance **. Is convenient.

However, there are problems with this. As explained in "I wrote about Java downcast in an easy-to-understand manner" I posted the other day, ** Functions unique to child classes when using upcast Cannot be called **.

I'm going to downcast there ... The main subject is from here.

What's inside?

Take a look at the program below and anticipate what will happen.

The details of the class are described in "Details of the class used for explanation".

Main.java


public class Main{
  public static void main(String[] args){
    Life_form life_form = new Life_form();

    java.util.Random r = new java.util.Random();
    if( r.nextInt(2) == 0 ){
      life_form = new Cat();

    }else{
      life_form = new Dog();

    }

//Proprietary function call from downcast.
    Cat lifo = (Cat)life_form;
    lifo.catPunch();

  }
}

The execution result is as follows

Execution result

スクリーンショット 2018-07-04 16.47.59.png

Let's explain the program. It generates a random number and upcasts a Cat instance if it's 0 and a Dog instance if it's 1.

I'm trying to downcast to the Cat class and call the Cat class's own function catPunch ().

When I run it, there are two cases, one is when catPunch () is called successfully and the other is when I get a ClassCastException error.

You can see that it works fine only if the generated instance is from Cat.

In other words, conversely, if a Dog instance is created, an error will occur.

Naturally. As you can see from the block of the if statement, the entity of the Life_form instance may be a Dog instance. Even if you try to downcast to a Cat instance, you cannot become a Cat instance even though the entity is a Dog instance.

** If you want to call a function unique to a child class, you need to know what the parent class instance really is **.

instanceof operator

In this way, even if the child class instance can be comprehensively held by upcasting, an appropriate cast cannot be performed unless the contents are known, and as a result, the function unique to the child class cannot be called. This is inconvenient.

** I want to find out the substance of the instance. There is an instanceof operator to achieve that **.

Instance instanceof type name

With this syntax you can find out what the instance is. True if the instance entity and type name match. Of course, if they do not match, false will be returned as the return value.

Based on this, the modified version of the previous program is shown below.

Success story

Main.java


public class Main{
  public static void main(String[] args){
    Life_form life_form = new Life_form();

    java.util.Random r = new java.util.Random();
    if( r.nextInt(2) == 0 ){
      life_form = new Cat();

    }else{
      life_form = new Dog();

    }

//Instance of type name
    if( life_form instanceof Cat ){
      Cat cat = (Cat)life_form;
      cat.catPunch();

    }else{
      Dog dog = (Dog)life_form;
      dog.dogAttack();

    }

  }
}

Execution result

スクリーンショット 2018-07-04 17.26.13.png

Properly, ** the behavior of each entity is output **. Note that the instanceof operator in the if statement conditional expression enables proper downcasting. Also, make sure that the function unique to the generated instance can be called properly.

In this way, you can achieve a safe downcast by using the ** instanceof operator **.

Summary

-The instanceof operator``` Instance instanceof type name


 --By using the instanceof operator, it is possible to change the behavior of each instance.

 --By using the instanceof operator, you can achieve a safe downcast when you want to use a function unique to an upcast child class instance.


# Details such as the class used for the description

#### **`Life_form.java`**
```java

//Parent class
public class Life_form{
  public void makeSound(){
    System.out.println("???");
  }
}

Cat.java


public class Cat extends Life_form{
  @Override
  public void makeSound(){
    System.out.println("nyaa");
  }

  public void catPunch(){
    System.out.println("Cat bread");
  }

}

Dog.java


public class Dog extends Life_form {
  @Override
  public void makeSound(){
    System.out.println("Kuhn!");
  }

  public void dogAttack(){
    System.out.println("Biting");
  }
}

Recommended Posts

The operator that was born to be born, instanceof (Java) ~ How to use the instanceof operator ~
[Java] How to use the File class
[Java] How to use the hasNext function
[Java] How to use the HashMap class
[Java] How to use the toString () method
Studying how to use the constructor (java)
[Processing × Java] How to use the loop
[Processing × Java] How to use the class
[Java] How to use the Calendar class
About the matter that I was addicted to how to use hashmap
[Java] How to use Thread.sleep to pause the program
How to use the replace () method (Java Silver)
[Java] How to use Map
[Java] How to use Map
How to use java Optional
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
[Java] How to use Optional ①
How to use the link_to method
How to use Java HttpClient (Get)
How to use the include? method
How to use the form_with method
How to use Java HttpClient (Post)
How to use the wrapper class
[Processing × Java] How to use variables
[Java] How to use LinkedHashMap class
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
To use the "java" command line tool ... How to avoid popping up
How to use submit method (Java Silver)
[Rails] How to use the map method
[Easy-to-understand explanation! ] How to use Java instance
[Java] How to get the current directory
How to use Java classes, definitions, import
[Easy-to-understand explanation! ] How to use Java polymorphism
[Java] [Maven3] Summary of how to use Maven3
How to install the legacy version [Java]
How to use Java Scanner class (Note)
How to get the date in java
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Java] Learn how to use Optional correctly
[Easy-to-understand explanation! ] How to use Java overload
try-catch-finally exception handling How to use java
[Easy-to-understand explanation! ] How to use Java encapsulation
How to use the camera module OV7725 (ESP32-WROVER-B)
[Java] How to use FileReader class and BufferedReader class
How to use Java framework with AWS Lambda! ??
Output of how to use the slice method
How to use Java API with lambda expression
[Java] (for MacOS) How to set the classpath
[Easy-to-understand explanation! ] How to use Java inheritance [Override explanation]
[Java] How to get the redirected final URL
[Java] Memo on how to write the source
[Java] How to get the authority of the folder