"super" and private variables

Asked

Viewed 40 times

0

In the case below, it makes sense to call super() in class B_Class since the variable a of A_Class is private? It would be more feasible not to use the parent-class builder?

Compiling this code error in the method return_number of B_Class saying that a is private in the mother class.

public class A_Class {
    private int a;

    A_Class(int num){
        this.a = a;
    }
}

public class B_Class extends A_Class {
    B_Class(int num){
        super(num);
    }

    public int return_number(){
        return this.a;
    }
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

2

The code doesn’t make much sense, starting with this.a = a is doing nothing useful, is assigning a variable by itself. To do this you do not need a constructor.

If you don’t have the constructor there, then you don’t have to have another constructor in the extended class, except for one specific reason.

That’s a question, maybe it helps to read What good is a builder?.

The error presented is different from all this and there is no relationship between them.

You are trying to access a field that does not exist in the derived class and therefore cannot be accessed. If you want this field to be accessed in the derived class then the field in the base should be at least protected.

A field declared private is only accessible in the class where it was declared, it is implementation detail of it, the derived class has no access to it. Of course the object will have that field for base class operations, but not for derivative class transactions. Except indirectly, this code seems to make more sense, although it maintains artificialism and can only demonstrate the mechanism and not OOP:

class Main {
    public static void main (String[] args) {
        var b = new B(5);
        System.out.println(b.getA());
    }
}
class A {
    private int a;

    A(int num) {
        a = num;
    }
    public int getA() {
        return a;
    }
}

class B extends A {
    B(int num) {
        super(num);
    }
    @Override
    public int getA() {
        return super.getA();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Do not treat this as a good model. When you are object-oriented programming you need to know what the problem is and what is needed. Artificially these projects always go wrong, because changing a small detail the whole code may not be valid anymore.

Browser other questions tagged

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