Search code examples
javaextendssuperclass

Java extends example


i have a java beginner question: Parent.print() prints "hallo" in the console, but also Child.print() prints "hallo". I thought it has to print "child". How can i 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";

}

Solution

  • Currently you've got two separate variables, and the code in Parent only knows about Parent.output. You need to set the value of Parent.output to "child". For 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 would be to give the Parent class a constructor which took the 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 really depends on what you want to do.