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
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.
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