• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About inheritance

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • 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?
 
Narayana Bojja
Ranch Hand
Posts: 130
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • 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: 232
2
  • Mark post as helpful
  • send pies
  • 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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic