how to achieve encapsulation in inheritance

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

提交回复
热议问题