Should protected attributes always be banned?

2019-03-18 10:27发布

I seldom use inheritance, but when I do, I never use protected attributes because I think it breaks the encapsulation of the inherited classes.

Do you use protected attributes ? what do you use them for ?

标签: oop protected
14条回答
Viruses.
2楼-- · 2019-03-18 11:18

C#:

I use protected for abstract or virtual methods that I want base classes to override. I also make a method protected if it may be called by base classes, but I don't want it called outside the class hierarchy.

查看更多
叼着烟拽天下
3楼-- · 2019-03-18 11:18

I use them. In short, it's a good way, if you want to have some attributes shared. Granted, you could write set/get functions for them, but if there is no validation, then what's the point? It's also faster.

Consider this: you have a class which is your base class. It has quite a few attributes you wan't to use in the child objects. You could write a get/set function for each, or you can just set them.

My typical example is a file/stream handler. You want to access the handler (i.e. file descriptor), but you want to hide it from other classes. It's way easier than writing a set/get function for it.

查看更多
登录 后发表回答