How to access mother class fields through inheritance?

Asked

Viewed 53 times

1

Simplifying what I mean, suppose I have a Mother class:

public class Mãe {

    private String nome;   // Declarando o campo privado nome

    public Mãe(String _nome) {

        nome = _nome;   // Definindo o campo nome 

    }

}

Now, the daughter class:

public class Filha extends Mãe {   // Extendendo da classe Mãe

    public Filha(String _nome) {

        super(_nome);   // Chamando o construtor da classe Mãe

    }

}

Therefore, in the class builder Filha I called the class builder Mãe, right? Then how would I, in class Filha, to access the field nome, class Mãe? I should put this field as an audience?

1 answer

0


Hello! Yes, the super serves to access the constructor of the Mother class. To access the attributes you can do as follows:

public class Filha extends Mãe {   // Extendendo da classe Mãe   
    public Filha(String _nome) {
        System.out.println(this.nome) // Pega o atributo nome que está na classe mãe
    }  
}

But the attribute must be as protected or public so that it can be accessed directly in child classes. The access modifier private allows direct access only to the class that declared the attribute. The protected also allows for heirs classes and the public free access to all.

  • I understand. Thank you very much for your reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.