Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call subclass constructor from abstract class in Java

Tags:

java

public abstract class Parent {

    private Parent peer;

    public Parent() {
        peer = new ??????("to call overloaded constructor");
    }

    public Parent(String someString) {
    }

}

public class Child1 extends parent {

}

public class Child2 extends parent {

}

When I construct an instance of Child1, I want a "peer" to automatically be constructed which is also of type Child1, and be stored in the peer property. Likewise for Child2, with a peer of type Child2.

The problem is, on the assignment of the peer property in the parent class. I can't construct a new Child class by calling new Child1() because then it wouldn't work for Child2. How can I do this? Is there a keyword that I can use that would refer to the child class? Something like new self()?

like image 905
Joel Avatar asked May 21 '09 07:05

Joel


2 Answers

I'm not sure if it is possible to do this without running into cycles. I am convinced that it would be a lot clearer to write this using factory methods instead of constructors.

like image 194
Kevin Peterson Avatar answered Sep 30 '22 02:09

Kevin Peterson


public abstract class Parent implements Clonable{

  private Object peer;

  // Example 1 
  public Parent() {
    try {
      peer = this.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
  }

  // Example 2
  public Parent(String name) {
    try {
      peer = this.getClass().getConstructor(String.class).newInstance(name);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  } 

  public <T extends Parent> T getPeer() {
    return (T)peer;
  }
}

public class Child01 extends Parent { }

public class Child02 extends Parent { }

It seems that the code may be more simple.

like image 26
Leonid Kuskov Avatar answered Sep 30 '22 01:09

Leonid Kuskov