Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 266
spod Avatar asked Nov 15 '16 19:11

spod


People also ask

How do you access the variables of parent class in child class?

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.

How do you access the variables of parent class in a child class in Python?

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.

What if parent and child class has same method?

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.

Can parent access class variables Java?

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.


1 Answers

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();
}
like image 173
homik Avatar answered Sep 20 '22 12:09

homik