开发者

Upcasting Downcasting

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. Why?

Also if my code is

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

This works fine.

Now what all 开发者_运维百科methods can my c variable access..the ones in C or the ones in class B?


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


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.

Upcasting Downcasting

“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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜