Two options:
If you need B
to keep the same interface as A
(so that client code can use any of the two without changes), you can override "forbidden" methods in B
and have them throw an UnsupportedOperationException
. For example:
public class A
{
public int allowedMethod() { ... }
public int forbiddenMethod() { ... }
}
public class B extends A
{
public int forbiddenMethod()
{
throw new UnsupportedOperationException("Sorry, not allowed.");
}
}
Or, if you really want the API of B
to be a subset of the API of A
, then just have B
contain an instance of A
, and delegate method calls appropriately.
public class A
{
public int allowedMethod() { ... }
public int forbiddenMethod() { ... }
}
public class B
{
private A a;
public int allowedMethod()
{
return a.allowedMethod();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…