Hello to everyone. I have a problem to which i cannot find any answers. I tried to google it but i didn't found anything which could help me.
So i have this small sequence of code:
class class1 { private int value; public class1(){ this.value = 10; } public int getValue(){ return this.value; } public int getAnotherValue(auxiliar aux) { return aux.visit(this); } public void setValue( int value) { this.value = value; } } class class2 extends class1 { public class2() { this.setValue(20); } } class auxiliar { public int visit ( class1 c1) { System.out.println("not here"); return c1.getValue(); } public int visit ( class2 c2 ) { System.out.println("here"); return c2.getValue(); } } public class Main { public static void main ( String[] args) { class2 c2 = new class2(); auxiliar aux = new auxiliar(); System.out.println(c2.getAnotherValue(aux)); } }
the output is the following:
not here
20
I would like it to be:
here
20
I noticed that when i copy the getAnotherValue(...) to class2 everything works as i want. But i don't think that's a smart approach. Also i think the problem comes from using 'this' in class1, getAnotherValue(...). But i don't know how it should be better to solve it.
What amazes me the most is the fact that if i add System.out.println(this.getClass().getName()); in the getAnotherValue(...) method the output is class2.