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";
}
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity.
Inheritance in Java is a concept that acquires the properties from one class to other classes; for example, the relationship between father and son. Inheritance in Java is a process of acquiring all the behaviours of a parent object.
Strings are immutable in Java it means once created you cannot modify the content of String. If you modify it by using toLowerCase(), toUpperCase(), or any other method, It always results in new String. Since String is final there is no way anyone can extend String or override any of String functionality.
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.
Child
doesn't have access to Parent
's output
instance variable because it is private
. What you need to do is make it protected
and in the constructor of Child
set output
to "child"
.
In other words, the two output
variables are different.
You could also do this if you change output to be protected
in Parent
:
public void print(){
output = "child"
super.print();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With