简体   繁体   中英

In Java can we write "SuperClassObject instanceof SubClass"?

Can I write a code like :

 class Shape
{
}
class Circle extends Shape
{
}
public class Main
{
    public static void main(String args[])
    {
        Shape shape = new Circle();
        if (shape instanceof Circle)
        {
            Circle C = (Circle)shape;
        }
    }
}

In the above code I have not provided the methods in the Shape and Circle class because I just want to ask whether I can use instanceof operator like this or not.

I mean this code is running well in my computer but my doubt is how can instanceof operator is working right in this case?

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, ie 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.

I mean this code is running well in my computer...

That code won't, it won't compile (because you're trying to use shape without initializing it).

But in general, yes, you can use instanceof to see if an object is an instance of a class. That's what it's for. If you changed the Shape shape; line to

Shape shape = new Circle();

....then the code would compile and if you ran it, control would pass into the if block because the object shape refers to is a Circle .

Note that it's the object that's checked, not the variable type.

First of all yes there is a compilation error in your code as I have already mentioned in the comment section.
Coming back to your question yes you can use instanceof to see whether an object is of specific type or not. I will recommend you to follow this .
Now if you want the shape instanceof Circle to be true then you need to initialize the shape like Shape shape = new Circle(); .
Else if you initialized the Shape shape = null; then shape instanceof Circle will be false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM