• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface to class assignment

 
Niranjan Deshpande
Ranch Hand
Posts: 1277
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//Question :
//By commenting out which line of code can you make the class
//ZZY compile with no - compile time errors ?Consider that the
//following lines of code exist in a file called ZZY .java

interface XTC { }

class ZZY implements XTC {

public static void main ( String ka [ ] ) { // ---> line 1
ZZY z = new ZZY ( ) ; // ---> line 2
XTC x = z ; // line 3
z = x ; // ---> line 4
Object o = x ; // ---> line 5
}
};

/*
Options :

a . line 1
b . line 2
c . line 3
d . line 4
e . line 5
*/

as per me, answer is d. and its correct too as per the voodoo
exam software. But if the class=interface; assignment
on line 4 doesnt work without an explicit cast, then
hoe come the class=interface; assignment on line 5 work ?
 
Mike Noel
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a matter of casting between interfaces and classes. Lines 3 and 5 are both instances of upcasting (assigning a subclass object to a super class reference) while line 4 is an example of downcasting (assigning a parent class object to a subclass reference). Downcasting requires an explicit cast in order to compile.

You would see the exact same behavior in your example if you changed XTC to a class and made class ZZY extend XTC.

_M_
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic