英文:
Java - Possible to create a parent class object that can store an instance of any subclass?
问题
我知道一个父类的数组可以存储其任何子类的实例,但是否可以使用单个对象实现这一点:
这是我希望理解的示例:
public class Parent
{
int a;
public Parent(int a)
{
this.a = a;
}
public void function1()
{
//操作
}
}
public class Child1 extends Parent
{
public Child1(int a)
{
super(a);
}
public void function2()
{
//操作
}
}
public class Child2 extends Parent
{
public Child2(int a)
{
super(a);
}
public void function3()
{
//操作
}
}
现在,如果我执行以下操作:
Parent p1;
Child1 c1 = new Child1(5);
p1 = c1;
p1.function1();
p1.function2();
我是否能够运行Parent
类的function1
方法以及Child1
类的function2
方法,使用Parent
类对象p1
?
如果这个问题很愚蠢,我很抱歉。我对这一切都很陌生。如果这是一个重复的问题,并且您标记它为重复,我也会感激。
英文:
I know an array of a parent class can store an instance of any it's sub-classes but is this possible with a single object:
Here's an example of what I'm hoping to understand:
public class Parent
{
int a;
public Parent(int a)
{
this.a = a;
}
public void function1()
{
//Actions
}
}
public class Child1 extends Parent
{
public Child1(int a)
{
super(a);
}
public void function2()
{
//Actions
}
}
public class Child2 extends Parent
{
public Child2(int a)
{
super(a);
}
public void function3()
{
//Actions
}
}
Now if I perform the following:
Parent p1;
Child1 c1 = new Child1(5)
p1 = c1;
p1.function1();
p1.function2();
Would I be able to run the the function1
method of the Parent
class as well as thefunction2
method of the Child1
class with the Parent
class object p1
?
Sorry if this is a silly question. I'm new to all this. Also, if this is a duplicate and you mark it as such, I'd appreciate that too.
答案1
得分: 0
经过一些更多的尝试、错误以及额外的研究,我意识到我所希望实现的并不可能。
因此,为了我的项目,我创建了每个类的单独实例,并在需要时单独访问它们。虽然这不是我设想中的解决方案,但它作为一个有效的解决方法来绕过了我的问题。
附言:对于指出这段代码不起作用的评论,他们是对的,确实不起作用。这只是一个抽象示例,用来说明我的问题。但也许我当初不应该将其格式化为代码。我会立即更正这一点。
英文:
After some more trial and error and additional research, I realize that what I'm hoping to achieve is not possible.
As such, for my project I created separate instances of each class and accessed them individually when required. That wasn't the solution I had in mind but it served as an effective workaround to my problem.
PS: To the comment that pointed out this code wouldn't work, they are right, it doesn't. It was meant as an abstract example to illustrate my issue. But perhaps I shouldn't have formatted it as a code then. I'll change that right away.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论