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

huangapple go评论67阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月12日 05:22:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64309131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定