JavaRush/Java Blog/Random EN/Instanceof Operator in Java

Instanceof Operator in Java

Published in the Random EN group
members
Hello! Today we will talk about the instanceof operator, look at examples of its use and touch on some points related to its operation :) At the early levels of JavaRush, you have already encountered this operator. Do you remember why it is needed? If not, it doesn’t matter, let’s remember together. The instanceof operator is needed to check whether the object referenced by variable X was created from some class Y. Sounds simple. Why did we return to this topic? First of all, because now you are well acquainted with the inheritance mechanism in Java and other OOP principles. The topic of instanceof will be much clearer and we will look at more advanced use cases. Go! How does the Instanceof operator work - 1You probably remember that the instanceof operator returns true if the test was true, or false if the result was false. Consequently, it is most often found in various types of test conditions ( if…else). Let's start with simpler examples:
public class Main {

   public static void main(String[] args) {

       Integer x = new Integer(22);

       System.out.println(x instanceof Integer);
   }
}
What do you think will be output to the console? Well, it's obvious here :) The object хis an Integer, so the result will be true . Console output: true Let's try to check if it belongs, for example, to String:
public class Main {

   public static void main(String[] args) {

       Integer x = new Integer(22);

       System.out.println(x instanceof String);// error!
   }
}
We received an error. And pay attention: the compiler issued it even before the code was executed! He immediately saw that Integer and String cannot be automatically converted to each other and do not have inheritance relationships. Therefore, an Integer class object will not be created from the String. This is convenient and helps to avoid strange errors already during program execution, so the compiler helped us out here :) Now let's try to look at more complex examples. Since we mentioned inheritance, let's work with this small class system:
public class Animal {

}

public class Cat extends Animal {

}

public class MaineCoon extends Cat {

}
We already know how instanceof behaves when we check whether an object belongs to a class in a normal situation, but what happens if we add a parent-child relationship here? How does the Instanceof operator work - 2 For example, what do you think the following check will produce:
public class Main {

   public static void main(String[] args) {

       Cat cat = new Cat();

       System.out.println(cat instanceof Animal);

       System.out.println(cat instanceof MaineCoon);

   }
}
Output: true false The main question that needs to be answered is how exactly does instanceof decipher the concept of “an object created based on a class”? As a result, we got it Сat instanceof Animal == true, but one can find fault with such a formulation. Why is this object Catcreated based on the class Animal? Isn't it only created based on its own class? The answer is quite simple, and you may have already figured it out. Remember the order in which constructors are called and variables are initialized when creating an object. We have already covered this topic in the article about the class constructor . Here's an example from that lecture:
public class Animal {

   String brain = "The initial value of brain in the Animal class";
   String heart = "The initial value of heart in the Animal class";

   public static int animalCount = 7700000;

   public Animal(String brain, String heart) {
       System.out.println("The constructor of the Animal base class is being executed");
       System.out.println("Have the variables of the Animal class already been initialized?");
       System.out.println("The current value of the static variable animalCount = " + animalCount);
       System.out.println("Current value of brain in class Animal = " + this.brain);
       System.out.println("Current value of heart in class Animal = " + this.heart);

       this.brain = brain;
       this.heart = heart;
       System.out.println("Animal base class constructor completed!");
       System.out.println("Current value of brain = " + this.brain);
       System.out.println("Current value of heart = " + this.heart);
   }
}

class Cat extends Animal {

   String tail = "The initial value of tail in the Cat class";

   static int catsCount = 37;

   public Cat(String brain, String heart, String tail) {
       super(brain, heart);
       System.out.println("The constructor of the Cat class has started (the Animal constructor has already been executed)");
       System.out.println("The current value of the static variable catsCount = " + catsCount);
       System.out.println("Current value tail = " + this.tail);
       this.tail = tail;
       System.out.println("Current value tail = " + this.tail);
   }

   public static void main(String[] args) {
       Cat cat = new Cat("Brain", "Heart", "Tail");
   }
}
And if you run it in the IDE, the console output will look like this: The constructor of the base class Animal is running. Have the variables of the Animal class been initialized already? Current value of the static variable animalCount = 7700000 Current value of brain in the Animal class = Initial value of brain in the Animal class Current value of heart in the Animal class = Initial value of heart in the Animal class The constructor of the base Animal class has completed its work! Current value of brain = Brain Current value of heart = Heart The constructor of the Cat class has started working (the Animal constructor has already been executed) Current value of the static variable catsCount = 37 Current value of tail = Initial value of tail in the Cat class Current value of tail = Tail Do you remember now? :) The base class constructor, if there is one, is always called first when creating any object. Instanceof follows this principle when it tries to determine whether an object was Аcreated from a class Б. If the base class constructor is called, then there can be no doubt. With the second check everything is simpler:
System.out.println(cat instanceof MaineCoon);
The constructor MaineCoonwas not called when creating Cat, which is logical. After all, MaineCoonhe is a descendant Cat, not an ancestor. But Catit is not a template for. Ok, this seems clear. What will happen if we do this:
public class Main {

   public static void main(String[] args) {

       Cat cat = new MaineCoon();

       System.out.println(cat instanceof Cat);
       System.out.println(cat instanceof MaineCoon);


   }
}
Hmm...this is more complicated. Let's try to reason. We have a variable of type Cat, and we have assigned an object of type to it MaineCoon. By the way, why does this even work? Is it possible to do this? Can. After all, any Maine Coon is a cat. If it’s not entirely clear, remember the example with primitive type extensions:
public class Main {

   public static void main(String[] args) {

       long x = 1024;

   }
}
The number 1024 is short : it easily fits into the long variable , because the number of bytes is enough for it (remember the example with nesting dolls?). A child object can always be assigned to an ancestor variable. Just remember this for now, and in the next lectures we will analyze this process further. So what will our example produce?
Cat cat = new MaineCoon();
System.out.println(cat instanceof Cat);
System.out.println(cat instanceof MaineCoon);
What will instanceof check: our class variable Cator our class object MaineCoon? Actually, the answer to this question is simple. You just need to read the definition of our operator again: The instanceof operator is needed to check whether the object referenced by the variable was Xcreated based on some class Y. The instanceof operator checks the origin of an object, not a variable. Therefore, in the example, both times it will display true in the console : we have an object of type MaineCoon. Naturally, it was created based on the class MaineCoon, but also based on the parent class Cattoo!
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet