[英]Child Instantiate from parent class
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. A1,A2不是所有的儿童班。 There are may be unlimited numbers.
可能有无限数量。
How can I write getObject() method to it creates A class childs instanses. 如何编写getObject()方法来创建一个类子实例。
PS: 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. 我只需要初始化子类对象,但是有大量的子类,我不会为所有这些类调用“new”,我也不会编写静态方法来初始化它,同样,所有的子节点都有相同的构造函数。 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). 当您编写
A a = A1.getObject()
,您确实使用子类名(A1)。 So a) your question is misleading and b) why can't you just write A a = new A1()
? 那么a)你的问题是误导性的,b)为什么你不能写
A a = new A1()
?
If you want to write A1.getObject()
, then you can redefine getObject()
in class A1: 如果要编写
A1.getObject()
,则可以在类A1中重新定义getObject()
:
public class A1 extends A {
public static A getObject() {
return new A1();
}
}
Without redefining, there is no way to declare getObject()
in class A so that it return objects different classes because A a = A1.getObject()
would compile to A a = A.getObject()
. 如果没有重新定义,就无法在类A中声明
getObject()
,以便它返回不同类的对象,因为A a = A1.getObject()
将编译为A a = A.getObject()
。
class A
{
protected int a;
public A()
{
a = 0;
}
public int getA()
{
return a;
}
public static A getObject(Class c) throws Exception
{
A obj = (A)c.newInstance();
return obj;
}
}
class A1 extends A
{
public A1()
{
a = 5;
}
}
class A2 extends A
{
public A2()
{
a = 10;
}
}
class Test{
public static void main(String args[]) throws Exception
{
A a = A1.getObject(A1.class);
System.out.println(a.getA()); // return 5
a = A2.getObject(A2.class);
System.out.println(a.getA()); // return 10
a = A.getObject(A.class);
System.out.println(a.getA()); // return 0
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.