Downcasting in Java

后端 未结 11 2118
自闭症患者
自闭症患者 2020-11-22 03:15

Upcasting is allowed in Java, however downcasting gives a compile error.

The compile error can be removed by adding a cast but would anyway break at the runtime.

11条回答
  •  长发绾君心
    2020-11-22 03:33

    Downcasting is very useful in the following code snippet I use this all the time. Thus proving that downcasting is useful.

    private static String printAll(LinkedList c)
    {
        Object arr[]=c.toArray();
        String list_string="";
        for(int i=0;i

    I store String in the Linked List. When I retrieve the elements of Linked List, Objects are returned. To access the elements as Strings(or any other Class Objects), downcasting helps me.

    Java allows us to compile downcast code trusting us that we are doing the wrong thing. Still if humans make a mistake, it is caught at runtime.

提交回复
热议问题