File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Not happy with the explanation given..

 
Rajesh k Jha
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 11833
181
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Try above code . Shortly, You can put subtype object into super type but not vice versa

Hope this helps
 
Jason Irwin
Ranch Hand
Posts: 327
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rajesh k Jha
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this question from Whizlab mock test 1.5
 
Rajesh k Jha
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic