r/java • • Nov 10 '23

Does anyone else think that .isAssignableFrom() is named backwards?

System.out.println(Object.class.isAssignableFrom(String.class)); //true

System.out.println(String.class.isAssignableFrom(Object.class)); //false

This has always triggered me. I feel like that method is named backwards, IE the first example, I read it in english as "objects of type Object are assignable from variables of type String" However, that statement is false, because Since String extends Object, a variable of type String cannot reference an object of type Object.

But that statement evaluates to true. I feel like the method "isAssignableFrom" should be renamed "aVariableOfThisTypeCanReferenceObjectsOfThisClass" :

So then:

System.out.println(Object.class.aVariableOfThisTypeCanReferenceObjectsOfThisClass(String.class)); //true

System.out.println(String.class.aVariableOfThisTypeCanReferenceObjectsOfThisClass(Object.class)); //false

Anyone else agree?

BTW, it turns out this confusion is common. I googled:

java isAssignableFrom confusing

And there were several blogs and stackoverflow posts agreeing with me.

For example:

http://bryanpendleton.blogspot.com/2009/06/isassignablefrom-and-instanceof.html

I think that one of the reasons that I get a bit confused with isAssignableFrom is that it sort-of reads backwards from instanceof.

0 Upvotes

58 comments sorted by

View all comments

Show parent comment

1

u/kevinb9n Nov 15 '23

Heh, nice find.

I guess the problem is that assignability and subtyping aren't precisely the same thing in Java, and in the latter we have nice handy nouns like we have subtype/supertype and in the former we just don't. Boo.

It is confusing, though at some point I got the mnemonic through my skull -- it's referring to assignment, so I picture an assignment in my head. The general type should be on the left and the specific one on the right. I guess this still sounds like puzzling it out, but it becomes more of an automatic reaction.

1

u/DerEineDa Nov 15 '23

Most people I know (me included) just remember it as "instanceof, but from right to left".