Private encapsulation in inheritance

Asked

Viewed 60 times

0

The class SuperSuper has an attribute of type private defined whole. Any specialization of the class SuperSuper may reset the encapsulation to public and your data is automatically converted?

public class SuperSuper{
 public int a;
 private int b;

public class Super extends SuperSuper{

}
  • 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 for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

4

First attribute is something you were taught wrong: What is the difference between attribute and field in the classes?.

What you’re calling encapsulation is actually information Hiding, begin by further studying the subject at I could not understand very well the encapsulation in the POO.

You are setting the field visibility.

Super doesn’t see the field b, so he can’t do nothingness with him. If he were a protected He would, but he still couldn’t change visibility. At most there could be another field that would transfer from one to another in a process and this new field in Super could have another visibility. But it would make more sense to just have a method that accesses the protected field.

I tend to criticize people who use private for everything when sometimes it is not necessary (it is good to make clear that because of the deficiency of the Java language tends to need much more than getters/setters), But this doesn’t seem like a case that should make him look any different. Of course, I can’t say categorically because the example is artificial, and in artificial examples you can’t learn from doing the right thing, that is, you’re not really learning what to do.

There is no conversion to do and nothing is done automatically.

If you change the contract in the specialization leaving it looser then you should not make inheritance there: Principle of Liskov’s replacement.

Object orientation is much more complicated than it seems, it’s not just memorizing simple mechanisms.

  • 1

    Just a caveat. About the private camps, I understand that you’re saying that sometimes it’s okay to be a public field. For certain situations it may make sense, although the issue of extensibility suggests caution with this. My concern is that this advice seems to mean that private camps are bad implementation when in fact they are great: they give as little visibility as possible to a field, which is prudent, and do not give gap to encapsulation violation (because a protected field, for example, is an implementation detail that should not be exposed to subclasses).

Browser other questions tagged

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