This is a weird question, immutable but mutable, private but public... The correct way should be to make them protected, as everyone said.
Anyway, in java you can use dirty tricks if the security manager doesn't complain, check this out:
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Priv
{
public static class A
{
private final int x;
public A(int x)
{
this.x = x;
}
}
public static class B extends A
{
public B(int x)
{
super(x);
}
public void setX(int x)
{
Class c = A.class;
try
{
Field f = c.getDeclaredField("x");
f.setAccessible(true);
f.set(this, x);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getX()
{
int v = 0;
try {
Class c = A.class;
Field f = c.getDeclaredField("x");
f.setAccessible(true);
v = f.getInt(this);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(Priv.class.getName()).log(Level.SEVERE, null, ex);
}
return v;
}
}
public static void main(String[] args)
{
B b = new B(5);
System.out.println("b.x is " + b.getX());
b.setX(42);
System.out.println("b.x now is " + b.getX());
}
}
A's contract is that it's immutable, andBextendsA, thenBmust be immutable. Otherwise, you're breaking the "is a" promise. Code can have a reference with typeAto aBobject, and despiteA's being immutable, find that the object mutates. Not good. :-)xandyto be immutable inA, you just needAnot to have any setters. There's a distinction there (in terms of the contractAprovides). If it's okay forBto modify thexandythat it inherits fromA, then MeNoMore's answer is the correct one.