I can not understand why you need this keyword. Explain by example, please.

Suppose I have a method in which you can pass an object of any type.

void foo(Object o){ //? } 

And I want to check what type the object belongs to. Probably, I did not correctly understand the essence of instanceof . But, nevertheless I will write as I consider

 if(o instanceof Integer){ //Your logic } 

If you understand correctly, then explain whether it is possible to use the instanceof to switch/case ?

Also, if you understand correctly, please explain why it is needed, if you can create several methods for different logic?

    1 answer 1

    Everything is simple: o instanceof Integer simply checks whether the real type of the object o type Integer .

    You really can create several methods for your logic, one for an Integer , the other for a String . But if Object comes to you, you will not be able to call the desired method, because you do not know what type your object really is. Here in order to find out, and need instanceof .

    By the way, using switch with instanceof will not work; switch requires primitive types or String *. But you can write an if chain:

     if (x instanceof Integer) { // что-то сделать с (Integer)x } else if (x instanceof String) { // что-то сделать с (String)x } else { // ну не шмагла я определить тип } 

    In a correct, well-written program, the number of instanceof and similar structures is usually small: it makes sense to avoid transferring untyped objects (for example, parameters of type Object ), and where the code should work with parameters of different types, use generics. However, sometimes you have to use the approach with the instanceof , for example, when interacting with the API, which was written before the arrival of generics.


    More on the topic:


    * Or enum , or wrappers for primitive types like Character .

    • switch требует примитивные типы - what about String ? - post_zeew
    • @post_zeew: And the truth. Added a clarification. - VladD
    • By the way, I didn’t specifically write about the shells, because, as I understand it, auto-packaging takes place in the switch , so your expression is fair for them :) - post_zeew
    • @post_zeew: But enums are probably important. Because Java has more enum than enum. - VladD