Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java polymorphism creating a new subclass object using a superclass variable

I want to create a new instance depending on an object, where I have the super class variable. Is this somehow possible without implementing a getNew() function or without usage of an ugly if chain? In other words: How to implement the following newSubClass(..) function without using the getNew() function?

public abstract class SuperClass {
    abstract public SuperClass getNew();
}

public class SubClassA extends SuperClass {
    @Override
    public SuperClass getNew() {
        return new SubClassA();
    }
}

public class SubClassB extends SuperClass {
    @Override
    public SuperClass getNew() {
        return new SubClassB();
    }
}

private SuperClass newSubClass(SuperClass superClass) {
    return superClass.getNew(); 
}
like image 731
Klaus Avatar asked May 19 '26 14:05

Klaus


1 Answers

After having some time to think about and zv3dh's contribution I decided this second answer.

I'am getting now you want an new instance of an instance of a subclass' type of SuperClass without knowing the concrete sub-type at runtime.

For that you have "reflexion".

public abstract class A_SuperClass {
    public A_SuperClass createNewFromSubclassType(A_SuperClass toCreateNewFrom) {
        A_SuperClass result = null;
        if (toCreateNewFrom != null) {
            result = toCreateNewFrom.getClass().newInstance();    
        }
        // just an example, add try .. catch and further detailed checks
        return result;
    }
}

public class SubClassA extends A_SuperClass {

}

public class SubClassB extends A_SuperClass {

}

If you search for "java reflexion" you will get lots of results here on SO and on the web.

like image 166
Martin Meeser Avatar answered May 24 '26 09:05

Martin Meeser