Superclass static method returning 2 different subclasses

This is bad programming practice, but I was asked to do it as part of a larger assignment.

I am creating a superclass and then 2 subclasses. The superclass has a static method that must return one of two subclasses depending on the result. How can I write 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 it possible?

+3


source to share


3 answers


You can do it like this:

public abstract superClass
{
     public static superClass getBaseClass(...)
     {
           if(...)
           {
                 return new baseClass1();//baseClass1 should derive from superClass
           }
           else
           {
                 return new baseClass2();//baseClass2 should derive from superClass
           }
     }
}

      



Now you can do this

superClass sc=superClass.getBaseClass(..);

if(sc instanceof baseClass1)
{
     baseClass1 bc1=(baseClass1)sc;
     //work with bc1...
}

if(sc instanceof baseClass2)
{
     baseClass2 bc2=(baseClass2)sc;
     //work with bc2...
}

      

+1


source


I'm not sure if this is what you are looking for, but if you want to return the class, you can do so by writing the subclass name and adding .class

to get the class type. The correct return type is the type of Class

a generic , limiting the result of a superclass and its subclasses.

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

      



If you want to return an object of the appropriate class, you can do so by simply returning 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();
     }
}

      

+4


source


You are trying to determine the return type of a method. It cannot be done. Thus, you must have a generic superclass return type. BTW, if you know at compile time the correct return type, why don't you change (having 2 methods?) The method to reflect this?

0


source







All Articles