I have a class
public class A {
private String name;
public void setName(String name){
this.name = name;
}
public string getName(){return name;}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name).append(", ");
return builder.toString();
}
}
I have a child class B that extends A and I have to access name from A in toString method in B. I have written the following code but not sure if this a good practice?
public class B extends A {
private String gender;
public void setGender(String gender){
this.gender = gender;
}
public string getGender(){return gender;}
@Override
public String toString() {
c = new A();
StringBuilder builder = new StringBuilder();
builder.append(c.getName()).append(", ");
builder.append(gender).append(", ");
return builder.toString();
}
}
EDIT:
If I cannot access private String name in class B, do I have to @Override setName()
by using super.setName(name)
? In that case how different it is from using class B without extending class A if I dont want to use any of the objects of A?
I just started using JAVA to modify a service.
When you have a variable in child class which is already present in the parent class then in order to access the variable of parent class, you need to use the super keyword.
Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java. In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
You can access a parent's protected or private variables if those variables are declared as static . Without the static keyword, you'll need a reference to an instance of the class, instead of a static reference to the class itself.
simply by calling getName()
in your toString method or super.getName()
like:
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getName()).append(", ");
builder.append(gender).append(", ");
return builder.toString();
}
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