It is possiable to instantiate child object from parent class without child class name.
For example, I have next classes:
public class A {
protected int a;
public A1() {
a = 0;
}
public int getA() {
return a;
}
public static A getObject() {
// some code which I need to write
}
}
public class A1 extends A {
public A1() {
a = 5;
}
}
public class A2 extends A {
public A2() {
a = 10;
}
}
Usage example:
A a = A1.getObject();
a.getA(); // return 5
a = A2.getObject();
a.getA(); // return 10
a = A.getObject();
a.getA(); // return 0
A1, A2 it is not all child classes. There are may be unlimited numbers.
How can I write getObject() method to it creates A class childs instanses.
PS:
I just need to initialize child class object, but there are large amounts of child classes and I would not to call “new” for all of them and I would not to write static method to initialize it, also, all childs have same constructors. It is big lack that I can’t create child instance from parent.
When you write
A a = A1.getObject(),you do use child classname (A1).
So a) your question is misleading and
b) why can’t you just write
A a = new A1()?If you want to write
A1.getObject(), then you can redefinegetObject()in class A1:Without redefining, there is no way to declare
getObject()in class A so that it return objects different classes becauseA a = A1.getObject()would compile toA a = A.getObject().