• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

interface to class assignment

 
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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_
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic