Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Superclass static method returning 2 different subclasses

Tags:

java

This is bad programming practice but I've been asked to do it as part of a larger assignment.

I am creating a superclass and then 2 subclasses. There is a static method in the superclass that should return either of the 2 subclasses depending on the result. How would I go about writing this method?

For example I need to do something like this

public abstract class Superclass{
    public static subclass? createFromFilename(String fileName){
            if(1==1)
               return subclass1;
            else
                   return subclass2;
    }
}

Is this even possible?

like image 284
ApocSama Avatar asked Mar 17 '26 18:03

ApocSama


1 Answers

I am not sure if this is what you are looking for, but if you want to return the class type, you can do that by writing the subclass name and appending a .class to get the class type. A proper return type would be the type Class with a generic limiting the result to Superclass and its subclasses.

public static Class<? extends Superclass> createFromFileName(String fileName) {
     if (fileName.equals("A")) {
          return SubclassA.class;
     } else {
          return SubclassB.class;
     }
}

If, however, you want to return an object of the respective class, you can do that by simply return a new instance and set the return type to Superclass:

public static Superclass createFromFileName(String fileName) {
     if (fileName.equals("A")) {
          new SubclassA();
     } else {
          new SubclassB();
     }
}
like image 92
Konrad Reiche Avatar answered Mar 20 '26 07:03

Konrad Reiche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!