how to achieve encapsulation in inheritance

前端 未结 2 972
滥情空心
滥情空心 2021-01-17 07:47

I have two classes Test and Encap. I have a private variable a and access via setter and getter method. and i\'m inheriting the class

2条回答
  •  深忆病人
    2021-01-17 08:23

    If you mean that you want a derived class to not expose public methods of the superclass, then your code probably 'smells'...

    Remember that Inheritance models "Is A"

    So in your example an Encap is a Test and you should be able to do anything to an Encap that you can do to a Test.

    However, if you simply must inherit from a class where you don't want to expose a parent-class method, you can override the method and have its body do nothing. But for simple getter and setter accessor methods this is potentially very confusing for clients of your code.

    If you can't reconcile things and calling setValue() on an Encap is never the right thing to do, i would recommend overriding the method, commenting it liberally and have it do nothing, or throw an exception to indicate to the client that they're doing something that doesn't make sense.

提交回复
热议问题