从超类实例创建实例 [英] Create instance from superclass instance

查看:55
本文介绍了从超类实例创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情况:

class A {
  int x;
  int y;
}

class B extends A {
  int z;
}

现在,在代码中的某个地方,此类的用法如下:

Now, somewhere in the code this classes are used like this:

A objA = getAFromSomewhere();
B objB = null;

在某些情况下,我想做类似的事情

And in a certain situation I want to do something like

objB = objA; // can't do this
objB.z = someZ;

当然,真实的对象要复杂一些,所以不仅仅是复制两个整数.但是它们也不是太复杂.

Of course the real objects are a bit more complicated, so it's not just about copying two ints. But they aren't overly complex either.

我知道我可以像这样编写B的构造函数:

I know I can write a constructor for B like this:

public B(A anA) {
  this.a = anA.a;
  this.b = anA.b;

  this.z = 0;
}

但是,如果那真的是唯一的方法,我更喜欢将B的其他成员合并到A中.

But if that's really the only way, I prefer merging the additional members of B into A.

考虑答案进行更新

我的问题还不够清楚.我了解objB = objA;无法工作(因此我要求类似",意思是代码复杂度可比的东西),并且我知道浅拷贝和深拷贝的问题.
我一直在寻找一种复制基类成员的可能性(例如,使用clone()).您可能会理解,手动复制每个成员是一个不好的解决方案,因为它会增加代码的复杂性和冗余性.无论如何,谢谢您的答复!

My question was not clear enough. I understand that objB = objA; can't work (thus I asked for "something like", meaning something with comparable code complexity) and I know about the issues with shallow vs deep copies.
What I was looking for is a possibility to copy the members of a base class (let's say using clone()). You may understand that copying every member manually is a bad solution as it adds complexity and redundancy to the code. Thanks for your replies anyway!

推荐答案

对此没有简单的解决方案,因为没有一种千篇一律的解决方案.基本上,您没有在 B 中包含所有信息,因此您不能保证自己拥有明智的"信息. B 对象.

There's no trivial solution to this because there's no one-size-fits-all solution. Basically you don't have all the information within a B, so you can't guarantee you would have a "sensible" B object.

可能只是想在 B 中创建一个构造函数,该构造函数使用 A 并复制所有 A 数据导入新的 B .

You probably just want to create a constructor in B which takes an A and copies all the A data into the new B.

这篇关于从超类实例创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆