在Java中用超类方法创建一个新的子类

时间:2016-03-06 20:23:14

标签: java inheritance

我有一个抽象的超类,它具有我的子类使用的具体方法。至少在我的一个方法中,我想返回一个相同类型的新对象。

为了更好的例子,我有一个带有字段(int num)的A类。我有B类扩展A,我创建了一个名为classB的B类对象。 classB.someMethod应为square num并返回一个具有此平方值的新B类对象。我不想改变原始实例。

我读过有关反思的内容,因为这是我搜索过程中出现的问题。经常建议使用newInstance()。我也读到反思可能很糟糕。有没有更好的方法来解决我想做的事情?这是我为openGL编程创建的个人课程,可以通过多种方式实现,但总是尽量保持简单。如果需要,我可以详细说明我的课程。

public class A(){
    private int num;

    public A(int num){
        this.num = num;
    }

    public A square(A a){
        temp = a.num * a.num;

        return new class same type as the sublcass(temp);
    }
}

public class B extends A(){
    public B(int num){
        super(num);
    }
}

public static void main(String...args){
    B first = new B(4);

    B second = B.square();
}

2 个答案:

答案 0 :(得分:1)

使用钩子方法(超类中的抽象方法)来生成子类的实例。

如果要在超类中使用特定的返回类型,则需要一个类型变量,保存最具体的类引用。请记住,这会使您的代码更难理解。

像这样:

public class A<SUB extends A<SUB>> {
    private int num;

    public A(int num){
        this.num = num;
    }

    public SUB square(){
        int temp = num * num;

        return newInstance(temp);
    }

    protected abstract SUB newInstance(int temp);
}

public class B extends A<B> {
    public B(int num){
        super(num);
    }

    protected B newInstance(int temp)  {
        retunr new B(temp);
   } 
}

public static void main(String...args){
    B first = new B(4);

    B second = first.square();
}

答案 1 :(得分:1)

只要类型可以分配给父方法,您就可以覆盖方法。您可以使用以下模式查看其定义here并将其应用于您的代码。

public class A {
    private int num;

    public A(int num){
        this.num = num;
    }

    public A square(A a) {
        temp = a.num * a.num;

        return newInstance(temp);
    }
    protected A newInstance(int num) {
      return new A(num);
    }
}

public class B extends A(){
    public B(int num){
        super(num);
    }
    public B square() {
      return (B)super.square();
    }
    protected B newInstance(int num) { // Yes, this is allowed
      return new B(num);
    }
}

public static void main(String...args){
    B first = new B(4);

    B second = B.square();
}
相关问题