Why can’t you access a class attribute in the inherited class?

Asked

Viewed 177 times

2

I have this class:

package auladezoitodonove;


public class Conta {


    // atributos
    private int numeroConta;
    private String nomeCliente;
    private int identificador;

    //Construtores
    void Conta (){
       numeroConta = ++identificador;
    }
    void Conta(String cliente){
        numeroConta = ++identificador;
        nomeCliente = cliente;
    } 

And this other class inheriting from the class Conta:

package auladezoitodonove;

public class ContaCorrente extends Conta{
    private int taxa;

    public ContaCorrente(String cliente, int taxa) {
        super(nomeCliente);

        nomeCliente = cliente;
        this.taxa = taxa;
    }

I cannot understand why it is not possible to inherit the attributes of the class Conta for ContaCorrente.

2 answers

5


I see some problems in modeling, but I will focus on the question asked.

What you call attributes is actually called field.

Inheritance is occurring. People do not understand inheritance and therefore think that something is not inherited, but inheritance all what the mother has, including anything she has inherited. So she is inheriting everything.

The question is not especially clear but I think it can be inferred that you tried to access a declared mother-class field in the daughter-class and it must have given some error. Well, the mother-class camps were declared with visibility private (private) and therefore are only `visible in mother class code. It does not mean that the field does not exist in the daughter class, only her code cannot access.

The solution is to increase field visibility. One way that some would make them public, But I might not want this, it’s too broad a visibility. So you can do the middle, you can make the field visible in the child classes without becoming public, this is through the visibility modifier protected. But beware without being too aware of its use may do wrong things and violate various object orientation principles (not that you cannot do this, but need to understand what you are doing, not just make it work) or general principles of design, like the coupling.

-1

Note that you are Declaring the attributes as "private" so those same will not be accessible outside the class, ie if inherit the class it inherits does not have access, but... If you use the Advisory Methods (Getter and Setter) I believe that solves the problem.

Browser other questions tagged

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