Reputation: 1673
I have a question about a sneaky way to gain access to package-access members that occurred to me. Specifically, I want to extend a class - let's call it com.acme.Foo
- to add some functionality. This is pure addition: all current methods of Foo
would be supported just by delegating to the superclass's method. However, there is no accessible constructor of Foo
, so I can't extend the class and my implementation won't pass the "isA" test for being a Foo
. There is no interface that expresses Foo
-ness that I can use instead of inheritance.
This is where the sneaky thought occurred to me: Foo
has a package-access constructor, so why not just create a package com.acme
in my source folder and create an InheritableFoo
class in that package:
package com.acme;
public class InheritableFoo extends Foo {
public InheritableFoo() {
super();
}
}
Now I can implement my extension to Foo
by extending InheritableFoo
, since that DOES have an accessible constructor.
This feels all wrong, and somehow unethical: I'm not respecting the decision the original programmer made when he or she decided to not expose a constructor for Foo
. But it could be the case that they simply adopted the "deny everything until there's a reason for it" approach. Either way, is there anything fundamentally wrong with this idea? Am I going to cause myself problems in the future if I go this route, and if so, why?
Upvotes: 6
Views: 296
Reputation: 420951
You are correct regarding the fact that you can "sneak" in a class of your own into another package and get access to package restricted elements.
This will however only as long as the author of com.acme.foo
distribute his code as source or an unsealed package. Should the author of this package distribute it as a sealed jar (which is quite common I believe) your approach will no longer work.
From Sealing Packages within a JAR File
Packages within JAR files can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file.
Upvotes: 1