Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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_
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic