aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Not happy with the explanation given.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Not happy with the explanation given.." Watch "Not happy with the explanation given.." New topic
Author

Not happy with the explanation given..

Rajesh k Jha
Ranch Hand

Joined: May 10, 2009
Posts: 72
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: 11503
    
  95

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: 72
I got this question from Whizlab mock test 1.5
Rajesh k Jha
Ranch Hand

Joined: May 10, 2009
Posts: 72
Thanks, It gave me the concept of IS-A relationship, and i got the satisfaction
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Not happy with the explanation given..