Upcasting Downcasting

后端 未结 5 474
攒了一身酷
攒了一身酷 2020-12-21 17:41

I have a parent class class A and a child class class C extends A.

A a=new A();
C c=(C)a;

This gives me error. Wh

相关标签:
5条回答
  • 2020-12-21 17:52

    In java there is concept that without upcasting u can't perform downcasting

    A a=new A(); C c=(C)a;

    in this case u try to perform downcast with out upcasting

    0 讨论(0)
  • 2020-12-21 17:57

    It's giving you an error because a isn't an instance of C - so you're not allowed to downcast it. Imagine if this were allowed - you could do:

    Object o = new Object();
    FileInputStream fis = (FileInputStream) o;
    

    What would you expect to happen when you tried to read from the stream? What file would you expect it to be reading from?

    Now for the second part:

    A a=new A();
    C c=new C();
    C c=(C)a;
    

    That will not work fine - for a start it won't even compile as you're declaring the same variable (c) twice; if you fix that mistake you'll still get an exception when you try to cast an instance of A to C.

    This code, however, is genuinely valid:

    A a = new C(); // Actually creates an instance of C
    C c = (C) a; // Checks that a refers to an instance of C - it does, so it's fine
    
    0 讨论(0)
  • 2020-12-21 18:07

    A is not a subclass of C hence you cannot cast it down.

    0 讨论(0)
  • 2020-12-21 18:08

    While casting the objects what we need to keep in mind is to apply is a relationship to the instances. Like in your example C is A but A is not C.

    So in your case, A a=new A(); C c=(C)a; // classCasteException occures.

    I think this might help you.

    0 讨论(0)
  • 2020-12-21 18:13

    Here's a nice youtube video http://www.youtube.com/watch?v=jpFij6RD7CA which demonstrates the same. Below is a full textual information for the same.

    “Upcasting” means moving subclass object to the parent class object. “DownCasting” is opposite to “Upcasting” moving the parent object to the child object.

    enter image description here

    “Upcasting” is perfectly valid but “Downcasting” is not allowed in .NET. For instance below is a simple “Customer” parent class which is further inherited by a child class “GoldCustomer”.

    class Customer
    {
    
    }
    
    class GoldCustomer : Customer
    {
    
    }
    

    Below is an “upcasting” code where the child parent class gold customer is pushed to the customer class.

    Customer obj = new GoldCustomer(); 
    

    Below is a sample of “downcasting” code where parent class object is tried to move to a child class object, this is not allowed in .NET.

    GoldCustomer obj = new Customer(); // not allowed illegal
    
    0 讨论(0)
提交回复
热议问题