Home > Software design >  Java: Extend a static class from non static class
Java: Extend a static class from non static class

Time:10-19

I have a class that is non-static. Let's say class A.

public class A

Can I extend this class to create an inner class?

Let's say

public class B {
    public static class nestedB extends A
    {
     // stuff
    }
}

Is this a good idea, or is this a good design?

Thanks!

CodePudding user response:

It is just a possible construct or structure, and it is neither inherently good nor inherently bad. It very much depends on the context and what you're trying to do with such a structure.

Uses that come to mind:

  • for grouping/packaging convenience (e.g. settings, nested value objects, etc.)
  • for keeping child concepts under a parent class to represent certain relationships (e.g. parent-child, conceptual siblings, etc.)
  • to offer specialised capabilities (e.g. builders, decorators, etc.)
  • and likely a lot more

In the end, if a structure makes sense, then it makes sense.

CodePudding user response:

Non-static classes are called top-level classes. All static means is that there is no this reference from the nested class to its parent. It is just a way to communicate that the class is used along with another one. There is nothing keeping you from having a static nested class inherit from a top level class.

The class java.lang.Object is a toplevel class, and java.util.AbstractMap.SimpleEntry extends Object. So that is an example of a nested static class extending a top level class.

  • Related