简体   繁体   English

Java - 可以创建一个可以存储任何子类实例的父类对象吗?

[英]Java - Possible to create a parent class object that can store an instance of any subclass?

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 the function2 method of the Child1 class with the Parent class object p1 ?我将能够运行的function1的方法Parent类以及该function2的方法Child1与类Parent类对象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.另外,如果这是重复的并且您将其标记为这样,我也会很感激。

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. PS:对于指出此代码不起作用的评论,他们是对的,它没有。 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.我马上改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM