Downcasting in Java

后端 未结 11 2127
自闭症患者
自闭症患者 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:35

    Consider the below example

    public class ClastingDemo {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        AOne obj = new Bone();
        ((Bone) obj).method2();
    }
    }
    
    class AOne {
    public void method1() {
        System.out.println("this is superclass");
    }
    }
    
    
     class Bone extends AOne {
    
    public void method2() {
        System.out.println("this is subclass");
    }
    }
    

    here we create the object of subclass Bone and assigned it to super class AOne reference and now superclass reference does not know about the method method2 in the subclass i.e Bone during compile time.therefore we need to downcast this reference of superclass to subclass reference so as the resultant reference can know about the presence of methods in the subclass i.e Bone

提交回复
热议问题