• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

About inheritance

 
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys, I was looking at a somewhat confusing question on Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 26233-26241). Enthuware. Kindle Edition.

What will be the result of attempting to compile and run the following program?

Select 1 option
A. The program will fail to compile.
B. Class cast exception at runtime.
C. It will print 30, 20.
D. It will print 30, 30.
E. It will print 20, 20.



I answered C and that's the correct answer, but something got me thinking though.
This is obviously fine because C is a subclass of A anyway
But this one: o1 is of reference type A so if you cast A to B, which is allowed, it compiles but then as A doesn't point to B shouldn'e we get an exception at runtime?
 
Ranch Hand
Posts: 145
4
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

B o2 = (B) o1;
o1 is of reference type A so if you cast A to B, which is allowed, it compiles but then as A doesn't point to B shouldn'e we get an exception at runtime?



You don't get exception here. Because B is super class of C. observe object type is C. For sub class object , you can give super class reference variable.

See the below code.



In the above code, It compile fine . But You will getClassCastException at run time because object type is A which is super class of B.  For super class object , you can't give sub class reference variable.

Hope this helps !
 
Jason Attin
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, yes I actually tried exactly the same thing, using alternatively

You don't get exception here. Because B is super class of C. observe object type is C. For sub class object , you can give super class reference variable.


I thought that when it comes down to casting what was important was the reference of the object and not the class of the object. But it seems that it is in fact both of them?
 
reply
    Bookmark Topic Watch Topic
  • New Topic