使用接口中定义的方法调用 clone 方法

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

Using methods defined in a interface to call the clone method

问题

为了简短明了,我有一个形状列表 List<Shapes>,其中包含实现了我的 Shape 接口的各种形状(圆形、正方形等)。

现在我正试图对列表中的每个形状进行深层克隆/复制,并将其放入一个新列表中。
我已经让所有形状实现了 Clonable,并为它们编写了自己的深层复制方法。

问题是,当它们仅被定义为 Shapes 时,我无法访问克隆方法。
我的问题是,如何在不必将它们转换为具体形状的情况下获取克隆方法。

我一直在思考并搜索,但似乎找不到一个合适的答案。
所以我有一个想法。

我能否在我的形状接口中添加一个方法 "void callCloneMethod();",
然后让具体实现调用每个具体形状的 clone() 方法呢?
换句话说,一个接口实现的方法能否调用非接口实现的方法?

提前谢谢你的回答。

英文:

So to keep it short and simple i have a list of shapes List<Shapes> these are all shapes (Circle, square ect) that implement my Shape interface.

Now im trying to deep clone/copy every shape on this list and place it in. a new list.
I have made all the shapes implement Clonable and made my own methods for making deeps copies of them.

The problem is i cant reach the clone method when they are simply defined as Shapes.
My question is how do i get a hold of the clone method without having to cast them into concrete shapes.

I have been thinking about it and googling it but i cant seem to find a proper answer.
And so i got an idea.

could i add a method "void callCloneMethod();" in my shapes interface
and have the implementation call the clone() method of each concrete shape?
IOW can a interface implemented method call non interface implemented methods. ?

Thank you in advance.

答案1

得分: 1

你是否尝试让你的Shape接口扩展Cloneable接口?这应该允许你对任何Shape调用该方法,如果我没记错的话。然后,你当然应该实现clone方法。
希望这能帮到你。

英文:

Did you try to let your Shape interface extend the Cloneable interface? This should allow you to call the method for any Shape, if i am not mistaken. You should then of course implement the clone method.
Hope this helps.

huangapple
  • 本文由 发表于 2020年3月15日 07:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/60688191.html
匿名

发表评论

匿名网友

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

确定