API of instanceof :
Implementation of the Instanceof operator. Returns a Boolean if the Object parameter (which can be an expression) is an instance of a class type.
Input 1: An object or Expression returning an object.
Input 2: A Class or an Expression returning a Class
Returns: A Boolean that is the result of testing the object against the Class.
The object that you are providing is checked for if it is of the class you are checking against. What I think is confusing you, comes down to covariance of Java (you could maybe read up on this more). You can declare a variable as a SuperClass type, and assign a SubClass object to that variable.
In terms of your example, something like this:
Shape shape = new Circle();
However, even though the variable shape is declared as a SuperClass type, what is stored inside this variable is an object of the SubClass, i.e. Circle. Therefore, when the instanceof method checks the object of the variable shape
, to see if it's an instance of (initiated as) Circle
, it returns true.
This is why the instanceof is very useful. Say you had another subtype:
class Square extends Shape { \*...*\ }
And you have some method where you want to do something specific if it's a Circle and something different if it's a Square, then you can have something like the following:
public void doSomethingWithShape(Shape shape) {
if (shape instanceof Cirlce) {
// code that handles circles here
} else if (shape instanceof Square) {
// code that handles squares here
}
}
Note: If it's a method in common and each subtype should have it (simple example would be printValues()), then rather have the method in the super class (in your case in Shape
), and then have each subtype class implementation override that method with the specific implementation details of that subclass, then
Shape shape = new SomeSubTypeOfShape();
shape.printValues();
the method that will be applied will be based on what is the object type in shape (the SomeSubTypeOfShape) and will invoke the overridden method associated with the subtype.
The example doSomethingWithShape
is only to show how instanceof can be used - to test a specific object for it's class. Even though the variable was declared as a superclass of the actual subclass object that was assigned to the variable, the object is still an object of the subclass.