Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Thu Jun 05, 2014 9:15 am
by vchhang
I understand fi in A is final but the object reference by b is still B. Why is a cast of the object B referring to A's field?

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Thu Jun 05, 2014 10:04 am
by admin
Access to variables depends on the class of the reference (and not on the class of the object). Casting a reference effectively changes the class of the reference used to access the variable. You need to read about variable hiding or shadowing. This link should help: http://blog.sanaulla.info/2008/06/27/sh ... mystified/

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Sat Sep 12, 2015 4:14 am
by Srijith
Hello,

Was shadowing possible if the class B doesnt extend A ?

Thanks ,
Srijith

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Sat Sep 12, 2015 4:27 am
by admin
Shadowing can also happen when you have an instance member and a local method variable with the same name. Within the method, the local variable shadows the instance member. You may read more about it here: http://docs.oracle.com/javase/specs/jls ... ml#jls-6.4

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Fri Jun 29, 2018 1:38 am
by ananias
what would be the output if it was like:

System.out.println( ( (A) new B() ).fi );

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Fri Jun 29, 2018 2:23 am
by admin
What did you get when you tried it out?

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Fri Jun 29, 2018 2:40 am
by ananias
it printed 10, why?

I thought it would print 15 since i'm just using a new object of B.

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Fri Jun 29, 2018 3:08 am
by admin
Access to all variables (and to all static methods) always depends on the type of the variable and not on the type of the object. This is a fundamental concept in polymorphism. I would suggest you to go through a good book to learn the basics before attempting mock exams.

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Sun Sep 09, 2018 4:45 pm
by herbertscbr
vchhang wrote:
Thu Jun 05, 2014 9:15 am
I understand fi in A is final but the object reference by b is still B. Why is a cast of the object B referring to A's field?
example without casting:
A b1 = new B();
System.out.println(b1.fi );//print 10

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Mon Aug 03, 2020 6:14 am
by Dreamweaver
I have not yet understood what makes the "final" keyword for a difference in this question.
When I delete "final" it have the same result

PS
final in class B is clear

Re: About Question enthuware.ocajp.i.v7.2.1291 :

Posted: Mon Aug 03, 2020 12:47 pm
by admin
It makes no difference. It is there just to confuse the candidate because final, when applied to a method, produces a different behavior.