So I was testing with some code snippets to wrap my head around the concept of inheritance, when I came across this - for me - strange phenomenon.
So first I was testing this simple code:
public class Main{
public static void main(String[] args) {
Bar bar = new Bar();
System.out.println("age = " + bar.age);
bar.test();
}
}
class Foo{
int age = 2;
void test(){
System.out.println("TEST FOO");
}
}
class Bar extends Foo{
int age = 4;
void test(){
System.out.println("TEST BAR");
}
}
And the output was as I expected:
age = 4
TEST BAR
Then I made a small change to line 3, where I changed the type Bar
to Foo
like this:
Foo bar = new Bar();
Now when I run the code, it gives me an output I believe is weird:
age = 2
TEST BAR
How does it happen that the code bar.age
is now using the age
member of the Foo
class (which makes sense), while bar.test();
still uses the method of the Bar
class (and not from Foo as that is what the type is)?
Change in an organization leads to many positive aspects – that lead to retaining a competitive edge and also remaining relevant in your business area. Change encourages innovation, develops skills, develops staff and leads to better business opportunities, and improves staff morale.
Change is constant and will always occur, and understanding its components on an individual level can help us relate it to an organizational level. Change is important to understand, as it affects many facets of an organization.
People react to change in many different ways and for very individual reasons. This can directly impact the dynamic and efficiency of a team. For individuals changes can create anxiety and uncertainty which can inspire deterioration in many of their attitudes to their work and to the organisation.
Organizational changes are those that have a significant impact on the organization as a whole. Major shifts to personnel, company goals, service offerings, and operations are all considered different forms of organizational change.
The age
in Bar
shadows the age
in Foo
.
Furthermore, fields are not polymorphic (cf. functions).
So when you write Foo bar = new Bar();
, the static type of bar
is used when accessing the field age
, to return 2. And the dynamic type of bar
is used when deciding which override of test()
to call, and that's a Bar
type.
Because you have defined two different age fields, one in each class. Fields are not overridden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With