Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Explicit Reference Casting

Tags:

java

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;
like image 712
udeleng Avatar asked Apr 05 '11 01:04

udeleng


People also ask

What is explicit casting and implicit casting in Java?

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.

What is reference casting in Java?

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.

Does Java do implicit 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.

Is Downcasting possible in Java?

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.


1 Answers

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.

like image 151
Bala R Avatar answered Nov 07 '22 21:11

Bala R