Java extends example -
i have java beginner question: parent.print() prints "hallo" in console, child.print() prints "hallo". thought has print "child". how can solve this?
public class parent { private string output = "hallo"; public void print() { system.out.println(output); } } public class child extends parent { private string output = "child"; }
currently you've got 2 separate variables, , code in parent
knows parent.output
. need set value of parent.output
"child". example:
public class parent { private string output = "hallo"; protected void setoutput(string output) { this.output = output; } public void print() { system.out.println(output ); } } public class child extends parent { public child() { setoutput("child"); } }
an alternative approach give parent class constructor took desired output:
public class parent { private string output; public parent(string output) { this.output = output; } public parent() { this("hallo"); } public void print() { system.out.println(output ); } } public class child extends parent { public child() { super("child"); } }
it depends on want do.
Comments
Post a Comment