In Java, getter and abstract Setter is correct?

Asked

Viewed 95 times

0

I have an abstract parent class Usuario. And a daughter class Usuario_Adulto.

The attribute idade is in the abstract class Usuario. To validate it I made a method Setter abstract in the parent class, because the attribute is protected, but what if it were private? How could I validate him in the daughter class?

It’s right to do this?

  • 1

    Read Maniero’s answer below and rethink whether you really need a subclass to distinguish adults from non-adults. Perhaps a method is enough ehAdulto or similar.

1 answer

3


I’m afraid of that kind of inheritance, I just can’t say she’s wrong because I don’t have enough information. You may be right, but I could only say by understanding every detail. Programming, especially object-oriented, is understanding every detail. For some reason some people think that’s not necessary.

I take this opportunity to say that what you call an attribute is actually correct to call a field.

I also want to say that people abuse and use wrong setters and getters.

If you have a reason for either of them to be abstract then they must be. The fact that it’s abstract can help the inheritance be a little more certain, I still can’t guarantee, but if Usuario cannot be instantiated is an indication of something good.

What do you want? If you want the implementation to be given only in the concrete class then it seems that you just do it.

If you just want to call in class Usuario a method that is still abstract to do some validation, can do it without problems, this whole mechanism was created to be just like that. Whoever calls doesn’t need to know how it’s being done inside, doesn’t even need to know that inside the class itself has no implementation, he just needs to call something he knows exists, which is the method contract. Obviously it will only work when implementing the method in an inherited class, which is the only way to instantiate this type.

And in fact if the method is to access a mother class field and the concrete class implementation needs to be able to access the field there in the mother class and then it cannot be private, would have to be protected.

At the same time it may not be the right form. It may be violating abstraction. Perhaps what you need is not an abstract method. You may want a method implemented in the mother class that accesses the private field, and then in the daughter class you reimplementate the method by doing what you want and calling at a certain moment the mother class method when accessing the state that is in a mother class field.

Something like that:

@Override
public void setA(int value) {
    if (value > 0) super.setA(value);
}

I put in the Github for future reference.

Browser other questions tagged

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