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

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -