Search code examples
javaoopooad

Handling inheritance with Parent Class and Child Classes with nested objects


Suppose I have a class Child extending Class Parent. The class Child has two nested classes nested1 and nested2. I want a abstract function to be defined in Parent with argument as nested1 and return type as nested 2. Right now , to achieve this , I have created a function with both argument and return type as Object.

So now , when I implement the child class , I am always required to cast the Object to nested1 and nested2. I feel there would be a better way to achieve this. Is there any better way to reduce the complexity?

Also attached the UML enter image description here


Solution

  • The best way from a typing point of view is to make a interfaces within the parent class that specify the nested classes in the child. That way you won't need to cast the argument to func. This doesn't reduce the complexity per-se but it does make your intention a lot cleaner and reduces/eliminates the need for casting (always a good thing).

    public abstract class Parent {
    
      interface Interface1 {
          //Specifications of methods that all child nested classes must have
      }
    
      interface Interface2 {
          //Specifications of methods that all child nested classes must have
      }
    
      public abstract Interface2 func(Interface1 obj);
    
    }
    
    public class Child extends Parent {
    
      private static class Impl1 implements Interface1 {
          //Implementations of methods in Interface1 as they pertain to Child
      }
      private static class Impl2 implements Interface2 {
          //Implementations of methods in Interface2 as they pertain to Child
      }
    
    
      @Override
      public Interface2 func(Interface1 obj) {
        //Should only have to use methods declared in Interface1
        //Thus should have no need to cast obj.
    
        //Will return an instance of Impl2
        return null;
      }
    } 
    

    On a more broad scale, you should ask yourself why every child needs its own set of nested classes. This will get way simpler if you can move the nested class definitions to the parent (and make them static) and just have the child classes customize them as needed during construction.