spod
spod

Reputation: 416

How to access parent class variable in child class inside a child method?

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.

Upvotes: 13

Views: 85006

Answers (3)

Eric M.
Eric M.

Reputation: 662

Never forget the old adage: You don't inherit your parent's privates.

If you want B to have access to A.name, you have a couple of options:

  • Change name to be either public (bad) or protected (better) in A.
  • Access name through A's setters and getters, e.g. this.getName()
  • Use reflection

What you've currently done just returns the default value of A.name and not the value of name that actually belongs to your instance of B.

Upvotes: 6

usha
usha

Reputation: 29349

When you inherit a class, you also inherit all the public and protected methods and variables from the inherited. So you can just do

@Override
public String toString() {
   StringBuilder builder = new StringBuilder();
   builder.append(this.getName()).append(", ");
   builder.append(this.getGender()).append(", ");
   return builder.toString();
}

Upvotes: 11

homik
homik

Reputation: 563

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();
}

Upvotes: 7

Related Questions