The reason the child does not print "child" is because in java inheritance only methods are inherited, not fields. The variable output not overridden by the child.
You can do it as follows:
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; } }
In addition, String variables need not be different names, but I did it 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 protected , that is, it can be read from both the parent and the child. The class constructor sets the variable to the desired value. Thus, you only implement the print function once and do not need a duplicated overridden method.
Mike miller
source share