Subclass outside the package cannot access protected members on instances of parent class (only on instances of subclass itself or its subclasses). JLS link: http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.2
Here is an example. There is an existing class looking as the following:
package package1;
public abstract class BaseImplementation {
public String getResource1() {
return processTemplate1(getBaseUrl());
}
public String getResource2() {
return processTemplate2(getBaseUrl());
}
// Kind of 'Template Method' pattern.
protected abstract String getBaseUrl();
}
So intention is to write decorator like the following:
package package2;
public class ImplementationDecorator extends BaseImplementation {
private BaseImplementation delegate;
public ImplementationDecorator(BaseImplementation delegate) {
this.delegate = delegate;
}
@Override
protected String getBaseUrl() {
return trackServer + "?redirect=" + delegate.getBaseUrl();
}
}
The code will not compile.
getBaseUrl() has protected access in base class, and even subclasses cannot access that on parent instances.
So question is how to decorate such instances with protected methods without using 'dirty' tricks like reflection or putting subclass to package with the same name as parent class.
There are also examples of the same in Java language itself (e.g. javax.security.auth.login.ConfigurationSpi), and in cases I've found in Java - access from the same package is used.