Search code examples
javaapiextend

Creating a class to extend for an API


I am trying to create an API in java for my Uni project.

Is the following possible.

I have 2 versions of MyClass where one does not contain code in the method bodies.

for example:

Full Version:

public MyClass {
     public String name;

     public MyClass(String name) {
          this.name = name;
     }

     public String getSpecialVersion(){
         return name + name;
     }
}

API Version:

public MyClass {
     public String name;

     public MyClass(String name) {}

     public String getSpecialVersion(){ return null; }
}

The idea being a user extends the API version of the class, but the full version of the class is loaded at runtime.

Is this possible in Java, or is there a better way to do it?

Thanks in advance!


Solution

  • You want to create an interface and let the "with code"-version implement that interface.

    public interface IMyClass {
    
        public String getSpecialVersion();
    
    }
    

    Implementation:

    public class MyClass implements IMyClass {
    
        public String name;
    
        public MyClass(String name) {
             this.name = name;
        }
    
        @Override
        public String getSpecialVersion() {
            return name + name;
        }
    
    }
    

    You cannot define constructors in interfaces (and defining fields in interfaces is kind of unconventional) tho, so you might want to look at abstract classes for that, too:

    public abstract class AbstractMyClass {
    
        public String name;
    
        public AbstractMyClass(String name) {
             this.name = name;
        }
    
        public abstract String getSpecialVersion();
    
    }
    

    This class can be extended by a concrete class to add the method body:

    public class MyClass extends AbstractMyClass {
    
        public MyClass(String name) {
            super(name);
        }
    
        @Override
        public String getSpecialVersion() {
            return name + name;
        }
    
    }