7

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.

13
  • Is making BaseImplementation.getBaseUrl() public out of the question?
    – pholser
    Jul 28, 2011 at 17:32
  • :) Yep, it would be too easy. We don't want expose that method to everyone.
    – Andrey
    Jul 28, 2011 at 17:35
  • I think I do not understand the question. I do not see a reason why this code should not compile. The extended class has access to the parent protected methods and it is perfectly valid that it invokes it. Jul 28, 2011 at 17:41
  • 3
    Isn't trying to decorate implementation details (ex, a protected method) a "dirty" trick itself?
    – Brian Kent
    Jul 28, 2011 at 19:08
  • 1
    Verified the same in C#, protected members on parent instances are not accessible even in the same namespace.
    – Andrey
    Jul 28, 2011 at 20:18

3 Answers 3

3

What you're trying to do here is intercept behavior that's more or less private in the relationship between type BaseImplementation and one of its derived types—here, your "delegate" instance that you'd like to decorate in your ImplementationDecorator class. The author of BaseImplementation never anticipated someone wanting to get in the middle there, and the author of the type derived from BaseImplementation didn't anticipate that any callers other than BaseImplementation itself would get in there.

Instead, the pattern you're looking for would look more like this, which I'm afraid you can't retrofit if you don't own the classes involved:

public interface URLProvider
{
  String getBase();
}


public final class BaseImplementation
{
  public BaseImplementation(URLProvider provider)
  {
    if (null == provider)
      throw new NullPointerException();
    this.provider = provider;
  }


  public String getResource1()
  {
    return processTemplate1(provider.getBase());
  }


  public String getResource2()
  {
    return processTemplate2(provider.getBase());
  }


  private final URLProvider provider;
}

With that in place, if someone had written an implementation of type URLProvider, it would be easy to decorate, because now method URLProvider#getBase() is public.

Now, you may say, well, isn't that the same as just changing your BaseImplementation#getBaseUrl() method to be public, rather than protected? Not quite. Here, the design acknowledges—or even warns—that the URLProvider instance is a capability that can be used from anywhere.

5
  • With this approach, BaseImplementation owns private instance of URLProvider. Now implementing decorator for URLProvider is pretty simple, but how to pass private instance of URLProvider which is owned by BaseImplementation to the decorator, without introducing public method to BaseImplementation ...
    – Andrey
    Jul 28, 2011 at 20:26
  • My assumption is that the decoration happens outside the scope of BaseImplementation, which, at this point, is a silly name to retain in my proposed revision, given that it's not longer a "base" for expected derivation. Say you have a ConcreteURLProvider in hand that someone else wrote. Before feeding it to BaseImplementation's constructor, you'd construct one of your URLProviderDecorator instances around it, and pass your instance to the BaseImplementation constructor instead. Let me know if you need me to show that as code in the answer body.
    – seh
    Jul 28, 2011 at 23:40
  • Accepting as a most reasonable approach. Anyway in some cases (in mine for example) introducing public setter for UrlProvider may be required (and I think appropriate), especially when set is done by some kind of injection behind the scenes (spring injection for example).
    – Andrey
    Aug 16, 2011 at 19:47
  • Note that Spring can do injection by way of constructor arguments, which usually makes for saner POJOs being subjected to the injection, so to speak: static.springsource.org/spring/docs/3.1.0.M2/…
    – seh
    Aug 17, 2011 at 0:18
  • Thanks, I know that, not a spring related topic here. To be more precise: public setter is needed when BaseImplementation's UrlProvider can be changed during lifecycle of a single BaseImplementation instance (classic State/Strategy pattern).
    – Andrey
    Aug 17, 2011 at 7:18
0

This is not the good answer (I answered in a comment), but there's a way around:

public abstract class BaseImplementation {

    (...)

    protected String getBaseUrl(BaseImplementation other)
    {
        return other.getBaseUrl();
    }
}

public class ImplementationDecorator extends BaseImplementation {
    private BaseImplementation delegate;

    (...)

    @Override
    protected String getBaseUrl() {
        return trackServer + "?redirect=" + getBaseUrl(delegate);
    }
}
3
  • There is no getBaseUrl() in BaseImplementation Jul 28, 2011 at 19:28
  • Interesting. To do not change BaseImplementation contract I would add protected static String getBaseUrl(BaseImplementation instance) {return instance.getBaseUrl(); } to parent. Accessing protected static members is legal from subclass in this situation.
    – Andrey
    Jul 28, 2011 at 19:32
  • There's in fact no reason for it to be an instance method since it doesn't do anything related to that instance itself; otoh, static members in java aren't polymorphic (class members in Smalltalk are), so if you ever wish to override it you're out of luck (I strongly dislike static on account of that and try only to use it in uninstantiable classes).
    – entonio
    Jul 29, 2011 at 1:42
-1

Protected functions should be visible.. No need to use 'dirty tricks' to get access to them.

Here's what protected members are capable of:

Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.

4
  • The method getBaseUrl() from the type BaseImplementation is not visible Jul 28, 2011 at 18:46
  • They are not visible. Refer to JLS: java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.2
    – Andrey
    Jul 28, 2011 at 18:47
  • You can't call delegate.getBaseUrl() directly.. but you can always use super.getBaseUrl() Jul 28, 2011 at 19:01
  • No need to use 'dirty tricks'... I thought exactly this way - until I tried to modify code to solve the problem in my IDE. After half an hour of trying, I don't think so anymore
    – gnat
    Jul 29, 2011 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.