Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting to superclass

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, I'm not sure I understand one of the answers on this question on
Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 26072-26074). Enthuware. Kindle Edition.
Which statement regarding the following code is correct?

Select 1 option
A. The code will print 10 and 40 if // 3 is commented.
B. The code will print 40 if // 2 and // 3 are commented.
C. The code will not compile because of // 1.
D. The code will compile if the line marked // 2 is commented out.
E. None of these.


SO the correct answer is A. The explanation says that
you can access ( (A) c). i because i is public in A. Remember that member variables are hidden and not overridden. So, B's i hides A's i and since B's i is private, you can't access A's i unless you cast the reference to A.

So, why in order to access A's i I have to cast C to A? I mean I appreciate that you can't access B's i because it's private but C has a version of i as well hasn't it, because it's inheriting from B which is inheriting from A...
 
Henry Wong
author
Marshal
Pie
Posts: 22119
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:
So, why in order to access A's i I have to cast C to A? I mean I appreciate that you can't access B's i because it's private but C has a version of i as well hasn't it, because it's inheriting from B which is inheriting from A...


Well, the simply answer is ... that is how it is defined. The Java Language Specification simply discusses how a variable is accessed/hidden. There is no clause in the specification that states that if the accessed variable is not allowed to be accessed, that it should go and get the hidden version instead. The specification simply states that it is a compiler error.

Henry
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:SO the correct answer is A. The explanation says that

I would have selected B

May be I'm wrong but I'm really not convinced by the answer A as correct answer since option A says only "The code will print 10 and 40 if // 3 is commented."

In explanation they are making changes in code by saying you can access doing ((A) c). i 
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic