"instance" "type" What is the use case?

During a short reading, I came across an interesting quote from Scott Meyers

Anytime you find yourself writing a form code, "if the object has enter T1, then do something, but if it's type T2, then do something else," pat yourself. "

I'm just wondering why Java has an β€œinstance” of an operator when you can do the same with overridden methods? When is it really used?

+6
source share
7 answers

Sometimes you have to use objects whose behavior (for example, source code) that you do not control, so you can not always rely on object-oriented solutions to issues related to the type. (Especially keep in mind that library authors cannot foresee all the use cases that you might have, of course, it can be argued that extension and implementation provide workarounds, but require much more effort than direct type checking.)

The instanceof operator gives you a way to check the type of an object and act conditionally.

+3
source

Ideal to avoid this, but sometimes necessary.

Using instanceof may interfere with the Open / Closed ("O" principle in SOLID). If you are implementing instanceof tests, then your class may need to be changed with new implementation classes.

However, sometimes it is necessary. For example, it can be used in implementations of the Object.equals() method. An argument is an object - so the method can be overridden by arbitrary subclasses - but you usually need to classify it as your class type for comparison.

+1
source

I really use it when I use a third-party library and the classes are final (jerky!).

The if-type-do-something code in the code is a sign that do-something should be a method defined in a class or interface with overriding behavior. But this assumes that you are in control of the implementation. Sometimes you don’t.

+1
source

When I implement equals() for the Foo class, it often looks like this:

 public boolean equals(Object o) { if (o instanceof Foo) { Foo that = (Foo) o; [ compare this to that ] } else { return false; } 

Since I override equals , the signature forces me, but I need to know if I have a Foo instance or not for meaningful comparison.

+1
source

For instance:

 public void eat(Eatable eatable){ if(eatable instanceof fruit){ //direct eat } } 

 class Eatable { } 

 class Fruit extends Eatable { } 
0
source

When writing a complex class structure like in the Wrapper design pattern, you never know which object u will encounter. In this situation, you are checking an object with an instance of an operator.

0
source

This is really useful for debugging, to check if the object is really who you think it is, and I'm sure there are several other uses in it.

-1
source

Source: https://habr.com/ru/post/890240/


All Articles