Java. Access to an instance variable variable through this statement

I need help with this little piece of code; why the conclusion is: 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(fa);// why b 3 and not b 13 ?? } } 
+4
source share
7 answers

Foo and Bar have two different a fields; Java has no concept of field redefinition.

A call to f.addFive() calls a derivative version of the method (because Java does an override of the method), which modifies Bar.a
However, accessing fa returns Foo.a (since f declared as Foo ), which never changed.

+9
source

In fact, you have two variables called a : one in Foo and one in Bar .

In Bar.addFive you change the variable a , which is declared in Bar (and not in the declaration in Foo ).

In addition, since the variables do not display polymorphic behavior, you access the variable a declared in Foo in the main method.

0
source

You change a to Bar , which does not match a to Foo , and your code prints a from Foo

Here are some more code examples that can help you understand whatโ€™s going on.

  Foo f = new Bar(); f.addFive(); System.out.println(fa);//3 System.out.println(((Bar)f).a);//13 Bar b = new Bar(); b.addFive(); System.out.println(ba);//13 
0
source

Java has no dynamic binding for variable instances, but only for methods. When you access a field, the most specialized (in case of a clash of names, as in your example) is not selected.

The selected one will be the one for which the variable was declared, not the runtime. For dynamic beaming, you use a getter, not a variable reference.

0
source

The rules are simple.

Polymorphism does not apply to:

  • static methods
  • private methods.
  • variables.
  • overloaded methods.
  • Generics

All this happens at compile time and is called time compilation or static binding.

Dynamic binding or execution binding is performed in method override mode.

0
source

I got you, first of all, in JAVA. However, what you do is not an override of methods, if you do this, it will work the way you want:

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

I hope you have a problem.

0
source
 Foo f = new Bar(); f.addFive(); 

f.addFive () executes the overriden method of the Bar class. In the next line

System.out.println (fa);

This returns the variable a of class Foo, which is 3 (since it does not change). Thus, you have received 3 responses.

0
source

Source: https://habr.com/ru/post/1397829/


All Articles