4

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?

csharpfolk
  • 4,124
  • 25
  • 31
  • Different question, but right answer: http://stackoverflow.com/questions/6987907/access-modifiers-for-inner-classes – BackSlash Dec 17 '16 at 14:54
  • If you want a real use case, check why there exists an `java.lang.AbstractStringBuilder` in Oracle's JDK. It's a (package-)private class used to handle all the common logic to `StringBuffer` and `StringBuilder`. All the methods are written in that class and both subclasses simply call `super` on those (for documentation reason in both cases and `synchronized` in `StringBuffer`'s case). This allows to write the logic only once, and yet present two different APIs to the user. – Olivier Grégoire Dec 17 '16 at 16:59

2 Answers2

1

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.

leeyuiwah
  • 6,562
  • 8
  • 41
  • 71
  • If `A` is implementation detail then is should be hidden by composition and/or delegation. IMHO in example you provided it would be better to define public interface and private implementations of that interface, client classes use only interface and truly doesn't know about implementations. – csharpfolk Dec 17 '16 at 15:08
  • 1
    Well, it certainly can! That doesn't mean it should. Java allows it as extension so it's a nice feature when properly used. Not later than 4 hours ago I wrote a common hidden parent just to avoid rewriting all my methods again and again. The result allows for a very fluent and nice API. – Olivier Grégoire Dec 17 '16 at 15:12
0

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.

ddarellis
  • 3,912
  • 3
  • 25
  • 53