简体   繁体   English

java polymorphism使用超类变量创建新的子类对象

[英]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? 如果不实现getNew()函数或不使用丑陋的if链,这是否可行? In other words: How to implement the following newSubClass(..) function without using the getNew() function? 换句话说:如何在不使用getNew()函数的情况下实现以下newSubClass(..)函数?

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(); 
}

After having some time to think about and zv3dh's contribution I decided this second answer. 经过一段时间思考和zv3dh的贡献后,我决定了第二个答案。

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. 我现在要了解一个子类类型SuperClass实例的新实例,而不知道运行时的具体子类型。

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. 如果您搜索“java reflexion”,您将在SO和网络上获得大量结果。

Have a look at the "FactoryMethod" design pattern. 看看“FactoryMethod”的设计模式。

It is exactly what you are looking for: It does encapsulate the "new" operator. 它正是您所寻找的:它封装了“新”运算符。

However your example makes me wonder: 但是你的例子让我想知道:

  • Your getNew() reimplements what the constructor would do anyway 你的getNew()重新实现了构造函数的功能

Try something like this: 尝试这样的事情:

public abstract class SuperClass {
    public SuperClass createSuperClass(object someParam) {
        if (someParem == a) return new SubClassA();
        if (someParem == b) return new SubClassB(); 
    }
}

public class SubClassA extends SuperClass {

}

public class SubClassB extends SuperClass {

}

As you see you need some IF at some place ... 如你所见,在某些地方需要一些IF ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM