Page 1 of 1

Method overriding and Shadowing

Posted: Tue Apr 26, 2016 9:56 am
by JaredTse
Can somone please tell me why the following snippet prints

=> 200
=> 100

instead of

=> 200
=> 300

Where am i missing the point ?

Code: Select all


class FieldScope2 {

    public int testA = 100;

    public void methodA(){
        testA =+ 100;
    }

}

public class FieldScope extends FieldScope2 {

    public int testA = 200;

    public void methodA(){
        testA =+ 100;
    }


    public static void main(String [] argv ){

        FieldScope fieldScope = new FieldScope();
        System.out.println( fieldScope.testA ); // => 200 ok 

        fieldScope.methodA();
        System.out.println( fieldScope.testA );   // => 300 Expected 

    }
}

Re: Method overriding and Shadowing

Posted: Tue Apr 26, 2016 10:49 am
by admin
Before one can try to explain the issue to you, you need to first explain why do you expect 300 to be printed?
-Paul.

Re: Method overriding and Shadowing

Posted: Tue Apr 26, 2016 11:13 am
by JaredTse
1, Well fieldScope is an object reference of type FieldScope and is pointing to FieldScope;

2, Now when I do fieldScope.testA i get back 200 , since the object reference is of type FieldScope, and it uses its own field testA,

3, Again the methodA increment the field by 100, fieldScope. now I would expect to see 300, but instead I get 100.

Thats my logic.

Re: Method overriding and Shadowing

Posted: Tue Apr 26, 2016 1:24 pm
by JaredTse
It worked, it was a a bug I have introduced whilst incrementing the number by 100.

instead of += I have used =+, which I assume is doing deduction or I am not sure.

Maybe someone can shade light as to why this is the case.

Re: Method overriding and Shadowing

Posted: Fri May 06, 2016 9:05 am
by limaia
JaredTse wrote:It worked, it was a a bug I have introduced whilst incrementing the number by 100.

instead of += I have used =+, which I assume is doing deduction or I am not sure.

Maybe someone can shade light as to why this is the case.
int i =0;
  • i += 2 is equivalent to i = i +2
  • i =+ 2 is equivalent to i = (+2) that is equivalent to i=2