how to achieve encapsulation in inheritance

前端 未结 2 952
滥情空心
滥情空心 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.

    0 讨论(0)
  • 2021-01-17 08:29

    One option would be to delete the method setValue() from the class Test:

    class Test
    {
        private int a;
    
        protected void getValue()
        {
            System.out.println("The assigned value of a is : "+this.a);
        }
    }
    

    Edit: Why to do this? If Encap inherits from Test, it should be able to do the same actions as Test. Otherwise, what's the purpose of inheriting? If you still thinking that Test should be able to modify the value and Encap not, maybe your design is wrong. You could try something like this instead:

                  BaseClass
                  ---------
                  +getValue
                    /   \
                   /     \
               Test       Encap
             --------   ---------
            +setValue   
    
    0 讨论(0)
提交回复
热议问题