Inherited method returning bad value
I have the following code:
Code:
class A {
int n = 0;
int foo(){
return n;
}
}
class B extends A {
int n = 5;
}
and now when I write
Code:
A b = new B();
b.foo();
, I expect it to return a value of 5, but it returns 0.
I think the problem lies somewhere in the upcasting of "b" to an "A" class, but I do not want to cast it like this: because besides the B class I have also another similar classes that extend the "A" class, so that would be solvable only by using multiple ifs, which is of course against the basic principles of OOP (polymorphism).
I hope you understand what I mean. So the question again is: How do I get b.foo() to return 5 ?