The reason why child is not printing "child" is that in inheritance in java, only methods are inherited, not fields. The variable output
is not overridden by the child.
You could do it like this:
public class Parent {
private String parentOutput = "hallo";
String getOutput() {
return output;
}
public void print() {
System.out.println(getOutput());
}
}
public class Child extends Parent {
private String childOutput = "child";
String getOutput() {
return output;
}
}
Also, the String variables do not need to be different names, but I did so here for clarity.
Another, more readable way would be to do this:
public class Parent {
protected String output;
public Parent() {
output = "hallo";
}
public void print() {
System.out.println(output);
}
}
public class Child extends Parent {
public Child() {
output = "child";
}
}
In this example the variable is protected
, meaning it can be read from both the parent and child. The constructor of the classes sets the variable to the desired value. This way you only implement the print function once, and do not need a duplicate overridden method.
Child
. TheParent
class is unaware of the variable inChild
. – Lobe