private instance variable of derived class not always returned by base class getter?
Hello,
sorry if the question if formulated in a complictated way. I rephrased
that several times and finally gave up. Here is my problem: I have
started to build an hierarchical object structure with a base class
and several derived classes. Each of the derived classes has a special
combination of private instance variables than can be accessed through
getters declared in the base class. I found something that I can=B4t
understand: when I define an instance variable of a derived class in
the (parameterless) constructor, this assignment seems to be ignored,
and the getter returns the value from the base class. When I provide
the value as argument in the constructor and assign the variable to
the provided value, things are as I would expect. What am I missing?
Many thanks for any insight!
Here is some sample code:
public class InheritanceConstructorTest{
public static void main(String[] args){
Derived d = new Derived();
Derived d2 = new Derived("derived with name");
System.out.println("D name: "+d.getName());
System.out.println("D1 name: "+d2.getName());
}
}
class Base{
private String name;
Base(String name){
this.name = name;
}
Base(){
this.name = "base";
}
public String getName(){
return this.name;
}
}
class Derived extends Base{
private String name = "Name for constructor without arguments";
Derived(String name){
super(name);
//this.name = name;
}
Derived(){
super();
//this.name = "Name for constructor without arguments";
}
}