Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. Instance variable value access via this operator

Tags:

java

i need someone help with this little code snippet; why is the output: b 3 and not b 13 as expected?

public class Foo{ 
    int a = 3;
    public void addFive() { a+=5; System.out.println("f");}  
}

class Bar extends Foo{
int a = 8;
public void addFive() { this.a+=5; System.out.println("b");}  

public static void main(String[] args) {
    Foo f = new Bar();
    f.addFive();
    System.out.println(f.a);// why b 3 and not b 13 ??
    }
}
like image 683
Mandark Avatar asked Jan 17 '23 10:01

Mandark


1 Answers

Foo and Bar have two different a fields; Java does not have any notion of field overriding.

Calling f.addFive() calls the derived version of the method (since Java does do method overriding), which modifies Bar.a.
However, accessing f.a returns Foo.a (since f is declared as Foo), which was never changed.

like image 192
SLaks Avatar answered Jan 20 '23 00:01

SLaks