How do I inherit a class in java, when the sub- and super-classes are in different packages
Asked
Active
Viewed 92 times
-4
-
4The same way as normal...? – Louis Wasserman Oct 04 '16 at 23:41
-
A class doesn't care who or where its subclasses are (as long as its not final), it can be extended from anywhere. And you can extend any superclass as long as you are able to import it into your Java file where you extend the class. – Kon Oct 04 '16 at 23:41
-
Classes aren't aware of their children. As long as the child can see its parent, it can copy it, naturally. – RaminS Oct 04 '16 at 23:43
-
@Kon: The class needs to be public, though, to be visible outside of the package. – Thilo Oct 04 '16 at 23:44
-
@Thilo Or protected. – RaminS Oct 04 '16 at 23:46
-
And not `final`. And have an accessible constructor. – Kevin Krumwiede Oct 04 '16 at 23:47
-
@Gendarme: Can a class be `protected`? http://stackoverflow.com/questions/3869556/why-a-class-cannot-be-defined-as-protected?noredirect=1&lq=1 – Thilo Oct 04 '16 at 23:49
-
1@Thilo They could, until you linked that post. Ugh... quantum mechanics. – RaminS Oct 04 '16 at 23:51
2 Answers
1
To make a class visible outside of its package, declare it as public
.
It can then be extended by classes in other packages (unless it is final
, then it cannot be subclassed at all).
Just like with any use of classes outside of the current (and the java
) package, you have to import
it (or use the fully qualified name my.other.package.ClassName
).

Thilo
- 257,207
- 101
- 511
- 656
0
Just like normal, use the import
statement.
import some.folder.SuperClass
public class SubClass extends SuperClass{
public SubClass(){
super();
}
}

Brydenr
- 798
- 1
- 19
- 30
-
Is `class SubClass extends some.folder.SuperClass` ever used, or is it too cluttery? – RaminS Oct 04 '16 at 23:48
-
1@Gendarme: It is too cluttery. You would use it only if you already have a class of the same name imported, such as `class Factory extends some.api.Factory`. But that should probably be avoided, too. – Thilo Oct 04 '16 at 23:50
-
@Gendarme see http://stackoverflow.com/questions/2079823/importing-two-classes-with-same-name-how-to-handle – Brydenr Oct 04 '16 at 23:53