Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...