Why cast after an instanceOf?

object casting in java
instanceof java
how to convert string to user defined object in java
java 8 instanceof
java casting
java checked cast
java cast(object to class)
cast vs instanceof

In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1, but only if those 2 are of compatible types.

if (p1 instanceof Square) {c1 = (Square) p1;}

What I don't understand here is that we first check that p1 is indeed a Square, and then we still cast it. If it's a Square, why cast?

I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless...

Edit: How would the compiler deal with:

if (p1 instanceof Square) {c1 = p1;}

Edit2: Is the issue that instanceof checks for the actual type rather than the apparent type? And then that the cast changes the apparent type?

Thanks,

JDelage

Keep in mind, you could always assign an instance of Square to a type higher up the inheritance chain. You may then want to cast the less specific type to the more specific type, in which case you need to be sure that your cast is valid:

Object p1 = new Square();
Square c1;

if(p1 instanceof Square)
    c1 = (Square) p1;

Casting In Java 8 (And Beyond?), If obj is null, it fails the instanceof test but could be cast because null can be a reference of any type. Dynamic Casting. A technique I encounter  The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object. JavaScript Demo: Expressions - instanceof. function Car (make, model, year) { this.make = make; this.model = model; this.year = year; } var auto = new Car ('Honda', 'Accord', 1998); console.log (auto instanceof

The compiler does not infer that since you are in the block, you have done a successful check for the type of the object. An explicit cast is still required to tell the compiler that you wish to reference the object as a different type.

if (p1 instanceof Square) {
    // if we are in here, we (programmer) know it's an instance of Square
    // Here, we explicitly tell the compiler that p1 is a Square
    c1 = (Square) p1;
}

In C# you can do the check and the cast in 1 call:

c1 = p1 as Square;

This will cast p1 to a Square, and if the cast fails, c1 will be set to null.

Object Type Casting in Java, An overview of type casting in Java, covered with simple and easy to understand examples. Learn about the instanceof operator in Java After the conversion in the above example, myInt variable is 1, and we can't restore  Java instanceof and its applications instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not. Following is a Java program to show different behaviors of instanceof.

There's a difference between measuring if some object will fit in a box, and actually putting it in the box. instanceof is the former, and casting is the latter.

Casting and runtime type checking (using instanceof)—ArcObjects , About casting a run time type checking (using instanceof). ArcObjects follow an interface based programming style. Many methods use interface types as  The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null

Because this particular syntactic sugar is not yet added to the language. I think it was proposed for Java 7, but it doesn't seem to have entered project coin

Thinking in Java 10: Detecting Types, Thinking in Java 10: Detecting Types - Checking before a cast. This is the keyword instanceof, which tells you if an object is an instance of a particular type. After creating the AssociativeArray, it is filled with key-value pairs of pet names​  Is there an instanceof analog for checking at compile-time? In my case, I'm trying to throw a ClassCastException as part of my definition of Queue's add method. My first thought was instanceof but I got error: illegal generic type for instanceof during compilation. – Ungeheuer Sep 21 '17 at 3:47

Old code wont work correctly

The impield cast feature is justified after all but we have trouble to implement this FR to java because of backward-compatibility.

See this:

public class A {
    public static void draw(Square s){...} // with impield cast
    public static void draw(Object o){...} // without impield cast
    public static void main(String[] args) {
        final Object foo = new Square();
        if (foo instanceof Square) {
            draw(foo);
        }
    }
}

The current JDK would compile the usage of the second declared method. If we implement this FR in java, it would compile to use the first method!

If something is an instance of a class why then cast it into that class , For example in the challenge it asks us to establish if obj is an instance of String, if it is, then cast it as a String!? Clearly I am missing something  Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. " Java Generics " offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop

JEP 305: Pattern Matching for instanceof (Preview), It is tedious; doing both the type test and cast should be unnecessary (what else would you do after an instanceof test?). This boilerplate -- in  In the above example, cast() and isInstance() methods are used instead of cast and instanceof operators correspondingly. It's common to use cast() and isInstance() methods with generic types. Let's create AnimalFeederGeneric<T> class with feed() method which “feeds” only one type of animals – cats or dogs,

Dynamic casting in Java, The instanceof operator requires a type, not a Class instance e.g. item instanceof Date; The cast syntax as well e.g. (Date) item. The instanceof  Boot, cast, or splint: A boot, cast, or splint may be put on your foot and lower leg to decrease your foot movement. These work to hold the broken bones in place, decrease pain, and prevent further damage to your foot. Medicine: Pain medicine: You may be given a prescription medicine to decrease pain.

Java “instanceOf”: Why And How To Avoid It In Code, The java “instanceOf” operator is used to test whether the object is an instance of Except this, we must admit that the readability suffers after adding In this case, we will still have the instanceOf and the casting, but we can,  $ g++ badcast.cpp -o badcast -Wall && ./badcast terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast Abort trap (core dumped) $ g++ badcast.cpp -o badcast -frtti -fexceptions -Wall && ./badcast terminate called after throwing an instance of 'std::bad_cast' what(): std::bad_cast Abort trap (core dumped) $ gcc -v Using built-in specs.

Comments
  • That's why he's asking a question delnan...
  • Regarding the question in your edit, why not just try to compile it yourself? You don't need the SO community to act as a compiler for you.
  • @Mark Peters - point well taken, my interest is not really what would happen, but more how differently the compiler would parse that.
  • That was what I didn't understand, thanks. I did a 2nd edit on my question to focus on that.
  • well, I think the compiler can know that it is a Square.
  • @Bozho, what do you mean? Not the current compiler. But I suppose it is possible.
  • well, from your answer it appeared that the compiler can't possibly know this. But it can, it's just not implemented yet (hence my answer)
  • It could be possible theoretically, but would not respect Java syntax and thus is not permitted by the compiler. Anyway since generics are in the language I'm not sure it is really a good thing to use instanceof. It is better to manipulate only well-defined interfaces.
  • Or in C#, if (p1 is Square s) { /* s is a non-null instance of Square, within this scope */ }
  • Assuming its a method's variable where no other thread can access, I always can put something in a box that fits instanceof!!!!
  • I hope it doesn't get added. Instanceof and cast is most often a design smell (should be using polymorphism). Making it more elegant will just aggravate the problem.
  • @Mark Peters - instanceof is a pretty valid usecase sometimes, although it is often misused.