views:

87

answers:

4

Okay so, I have this project structure:

package A.B

  • class SuperClass (this class is marked package private)

package A.B.C

  • class SubClass (inherits from super class)

I'd rather not make SuperClass publicly visible... It is really just a utility class for this specific project (A.B).

It seems to me that SubClass should be able to see SuperClass, because package A.B.C is a subpackage of A.B... but this is not the case.

What would be the best way to resolve this issue? I don't think it makes sense to move everything in A.B.C up to A.B or move A.B down to A.B.C... mainly because there will probably be an A.B.D which inherits from stuff in A.B as well...

I'm a bit new to Java, so be nice :D (I'm a C++ and .NET guy)

A: 

No, A.B can see what's inside A.B.C, not the other way around. Imagine boxes put into one another. The bigger boxes contain the smaller ones and so know what's inside them. The smaller boxes can't tell what's outside of them.

Peter Perháč
I think this is wrong -- A.B can't see in A.B.C any more than A.B.C can see in A.B.
Matt McHenry
So if I am trying to organize my project using folders of some sort, how am I supposed to do this?
Polaris878
+4  A: 

Packages are unique identifiers. You cannot make them follow the inheritance rules. Package and SubPackages are not analogical to Super and Sub classes.

I dont see any flaws in making the class that you wanted to use in the sub package to be visible to the outside world. I would be interested to know how this criterion is handled in C++/.net (as I am a java guy :) )

Bragboy
Yeah I kind of figured I was just misunderstanding packages
Polaris878
In .NET I would've just put the classes in folders and have them marked internal :)
Polaris878
@Polaris878 : Nice.
Bragboy
+2  A: 

Your best bet is to declare the (default) constructor(s) of SuperClass as protected. This way only classes in the same package and subclasses regardless of the package can instantiate it and extend from it.

BalusC
+1  A: 

Why not put them in the same package level?

Could you somehow use composition instead of inheritance? I've been trying to do more of this myself after reading Effective Java. Not sure if this is possible given your needs, but it might be worth considering.

Good luck.

Marshall Alsup
I don't want them in the same package level because I'll have around 20-30 classes that will rely on the super class, and I'm trying to keep things organized lol.
Polaris878