Search code examples
javaencapsulation

how to achieve encapsulation in inheritance


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 Test with Encap.

now i am able to change the value of a using setValue(int a). i want to restrict that option. i want it to make it as a read only value. please assist me in this.

class Test
{
    private int a;
    protected void setValue(int a)
    {
        this.a = a;
    }
    protected void getValue()
    {
        System.out.println("The assigned value of a is : "+this.a);
    }
}
public class Encap extends Test {
    public static void main(String [] args)
    {
        Test t = new Test();
        t.setValue(4);
        t.getValue();
        Encap e = new Encap();
        e.setValue(3);
        e.getValue();      
    }
}

Solution

  • 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