Reputation: 4280
I found the following program puzzling:
package package1;
public class Main {
private static class A { }
public static class B extends A { }
}
// ----------------
package package2;
public class Test {
public static void main(String[] args) {
Main.B b = new Main.B();
}
}
Why Java allows public class B
to extend private class A
? In other languages e.g. C# class may only extend private class when it is private itself.
Can you provide any scenario when extending private class may be useful?
Upvotes: 4
Views: 8483
Reputation: 3960
When you have functionality that is not really related to your class but cant stand alone, for example onclick events and so on... you create an inner class because the logic is only worth for this class. Beyond that you can extend and do whatever your program logic needs with that.
Also a very good OCP question.
Upvotes: 0
Reputation: 7152
This will allow A to be an implementation detail (not exposed to outside) yet reusable internally (be the basis of B). To users of B, what they care is B can fulfill all the contracts as exposed by its API. The fact that internally B uses A to fulfill those contracts should not bother any external users, right?.
Imagine that there can be many more sub-classes C, D, E, F, etc of A. Code of A can be reused by them.
Upvotes: 1