Downcasting in Java

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

    @ Original Poster - see inline comments.

    public class demo 
    {
        public static void main(String a[]) 
        {
            B b = (B) new A(); // compiles with the cast, but runtime exception - java.lang.ClassCastException 
            //- A subclass variable cannot hold a reference to a superclass  variable. so, the above statement will not work.
    
            //For downcast, what you need is a superclass ref containing a subclass object.
            A superClassRef = new B();//just for the sake of illustration
            B subClassRef = (B)superClassRef; // Valid downcast. 
        }
    }
    
    class A 
    {
        public void draw() 
        {
            System.out.println("1");
        }
    
        public void draw1() 
        {
            System.out.println("2");
        }
    }
    
    class B extends A 
    {
        public void draw() 
        {
            System.out.println("3");
        }
    
        public void draw2() 
        {
            System.out.println("4");
        }
    }
    

提交回复
热议问题