| Author |
Not happy with the explanation given..
|
Rajesh k Jha
Ranch Hand
Joined: May 10, 2009
Posts: 67
|
|
Interface Inter
{
}
class Base implements Inter
{
}
class Derived extends Base
{
}
public class Test
{
public static void main(Strng[] args)
{
Base b=new Base();
Derived d=new Derived();
Inter i=(Base)b;
i=(Base)d;
Derived bd=(Derived)b;//1
b=(Base)i;//2
}
}
It says commented line 2 is correct and says "commented line 2 will compile because the interface type variable has been case as Base type" Can somebody elaborate the concept...how is this correct
|
 |
Andrew Monkhouse
author and jackaroo
Marshal Commander
Joined: Mar 28, 2003
Posts: 10816
|
|
|
When you copy a question from a book, mock exam or other source, then you are required to quote your sources - so, please tell us where you copied this question from.
|
The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
Try above code . Shortly, You can put subtype object into super type but not vice versa
Hope this helps
|
 |
Jason Irwin
Ranch Hand
Joined: Jun 09, 2009
Posts: 327
|
|
Please use code tags.
Also, your code will not compile due to typographical errors.
Have you tried running this code to see what happens for yourself?
Base implements Inter, it passes the IS-A test.
Thus casting from any reference to Inter to Base could work, so the compiler allows it. The compiler is no aware of the instance "i" refers to, only the reference type.
In this example "i" refers to a Derived instance and Derived extends Base, so it passes the IS-A test for Base and for Inter (through inheritance).3
Thus the cast to Base will is acceptable at compile time and will work at run time.
If you added another class (e.g. "Other") and made the implement Inter, then set "i" to an instance of Other; you would get a class cast at line 2 at run time.
Although "Other" IS-A Inter (and thus passes compilation), it is not IS-A Base; so you get the exception.
|
SCJP6
|
 |
Rajesh k Jha
Ranch Hand
Joined: May 10, 2009
Posts: 67
|
|
|
I got this question from Whizlab mock test 1.5
|
 |
Rajesh k Jha
Ranch Hand
Joined: May 10, 2009
Posts: 67
|
|
|
Thanks, It gave me the concept of IS-A relationship, and i got the satisfaction
|
 |
 |
|
|
subject: Not happy with the explanation given..
|
|
|