How come there is no compiler error casting Number to List? I thought the types had to be relate.
Number k = 10;
List m = new ArrayList();
m = (List)k;
Type Casting Types in Java Java Type Casting is classified into two types. Widening Casting (Implicit) – Automatic Type Conversion. Narrowing Casting (Explicit) – Need Explicit Conversion.
Casting is the conversion of data of one type to another type either implicitly or explicitly. Casting happens for both primitive types and reference types. If the casting operation is safe, java will do automatic type casting. This is called implicit type casting.
The process of converting one type of object and variable into another type is referred to as Typecasting. When the conversion automatically performs by the compiler without the programmer's interference, it is called implicit type casting or widening casting.
In Java, the object can also be typecasted like the datatypes. Parent and Child objects are two types of objects. So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to Parent or can say Upcasting and Downcasting.
Just a guess but I think it's got something to do with m
being an interface reference. If you change it to ArrayList m = new ArrayList();
, it shows a compile time error.
I thought the types had to be relate.
Number is a class(abstract) and List is an interface so they can be related through another class.
so technically you could have
class Foo extends Number implements List
{
...
}
and
Number k = ... ; //
List m = new Foo();
m = (List) k;
could be legal and will run without exception if k is pointing to a type compatible with Foo
.
So if you refer to an object by an interface, resolution is deferred till runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With