-1

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?

Jorvis
  • 386
  • 5
  • 13
  • 2
    I don't think this code will run well. There is a compilation error because `shape` is not initialized – Lokesh Pandey Oct 24 '17 at 09:11
  • 2
    What happened when you tried it? @Lokesh Compilation errors are printed, not thrown. Don't misuse standard terminology. – user207421 Oct 24 '17 at 09:14
  • @Lokesh i think OP is aware that it wont compile as they write *"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 believe they are referring to the idea of determining whether the shape class can be an instance of its child. They would know straight away even without compiling it whether or not it should work. – Master Yoda Oct 24 '17 at 09:14
  • If you initialize shape with `= new Circle()` then I think you would understand why it would work. You are checking whether the class of the _object_ is an instanceof `Circle`. The type of the reference does not matter. – NickL Oct 24 '17 at 09:15
  • @EJP my apologies i have corrected that one – Lokesh Pandey Oct 24 '17 at 09:15
  • @MasterYoda read this line " I mean this code is running well in my computer " in OP's post – Lokesh Pandey Oct 24 '17 at 09:16
  • @Lokesh Yes, but to me that just nods at OP lazily adding only a small part of their code, going by the fact that they didnt add any methods to their superclass, nor did they override the child class. Could be wrong, maybe they did mean not to initialise their shape object. – Master Yoda Oct 24 '17 at 09:19
  • @MasterYoda but to me it's like providing incorrect information to the us. – Lokesh Pandey Oct 24 '17 at 09:24
  • 1
    Apart from that the compiler does not allow unintialized variables it's pretty easy to find out how `instanceof` works in this case. Just run it! It would be easier to answer the question if we know what you expect to be output instead of just stating that you doubt the "right" working of `instanceof`. – Ewald Benes Oct 24 '17 at 09:24
  • The point of this person's question, despite the code not being compilable (since shape is not initialized), is still easily deducible from the information and code given. The question is asking: *how can a variable that is declared as a superclass be an instance of a subclass - allowing the execution to enter into the if block of the code*. The answer is: because instanceof does not check the type of the variable, but checks the object type to which the variable is pointing. – Smiley Oct 24 '17 at 12:59
  • @MasterYoda yes you are absolutely correct. I basically wanted to ask whether the shape class can be instanceof its child or not. – Jorvis Oct 24 '17 at 18:45
  • 1
    @Jorvis Be careful with your terminology. "_the shape class can be instanceof its child or not_" is incorrect. An object is an instance of some class. A class is a class.. you can't have the `Shape` class be an instance of its child (child class/subclass). The variable `shape` can be declared as a `Shape` (the super class), but the object "stored in"/referenced by this variable `shape` may be an object that is an instance of a child class (due to covariance). The `instanceof` method checks the object (referenced to by the variable `shape`) against the class. – Smiley Oct 25 '17 at 10:41
  • @Smiley Really thanks a ton for clearing my concepts related to instanceof operator. – Jorvis Oct 25 '17 at 20:45

3 Answers3

4

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.

Smiley
  • 190
  • 1
  • 12
0

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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.

Lokesh Pandey
  • 1,739
  • 23
  • 50
  • Yeah! I forgot to initialize it. Actually on my PC I have initialized it but here on stack I forgot to write it down. – Jorvis Oct 24 '17 at 19:04