Search code examples
javainheritanceextends

How to upgrade Java class to extension class?


I have a simple problem. I have a large class:

public class Base {
    public Field1Data field1;
    public Field2Data field2;
    public Field3Data field3;
    // many more fields later...
    public Field1234Data field1234;
}

It has a very large number of fields, with a very large number of types.

Then I have an extension:

public class UpgradedBase extends Base {
    public String metadata;
}

I want a concise way to write the following method:

public static UpgradedBase upgrade(Base baseInstance, String metadata){
   /// What I don't know how to write.
}

I have Lombok, but that's about it as far as code-gen tools go. How can I write the upgrade method above? I'd prefer a concise method. I'm using Java 17.


Solution

  • First, you don't have a simple problem here. If you have a class which a large number of properties like this, that you are then sub-classing, there's a pretty good chance you have a large design problem.

    But, to answer the question you asked, you need to do two things.

    1. Create a "copy" constructor in Base
    2. Create an "upgrade" constructor in UpgradedBase

    For the copy constructor, you have:

    class Base {
    
      public Base(Base b) {
        this (/* whatever parameters are needed */);
        /*
         * Whatever approach you want to copy everything over...
         * you could do it with Reflection if you like
         */
      }
    }
    

    Then you would have:

    public class UpgradedBase extends Base {  
      public String metadata;
    
      public static UpgradedBase upgrade(Base baseInstance, String metadata) {
        return new UpgradedBase(baseInstance, metadata);
      }
    
      public UpgradedBase(Base baseInstance, String metadata){
        super(baseInstance);
        this.metadata = metadata
      }
    }