[英]How can I add method to an existing object in Java?
I'm using a Processing library to build my project in Java. 我正在使用处理库来用Java构建项目。 I use a function that returns me an object of type
PShape
(which I don't have access to source). 我使用一个函数,该函数返回一个
PShape
类型的对象(我无法访问源代码)。
I need to make this object of type Shape (a class I designed that extends PShape
). 我需要使这个对象的类型为Shape(我设计了一个扩展
PShape
)。
How can I make that? 我该怎么做?
Basically I have: 基本上我有:
PShape pShape = loadShape(filename);
Where loadShape
is a function I don't have access to source code. 在
loadShape
是一个函数的地方,我无法访问源代码。
I want to somehow do: 我想以某种方式做:
class Shape extends PShape {...}
and then 接着
Shape shape = (Shape) loadShape(filename);
But it won't work, once loadShape()
will give me a PShape
, not a Shape
但这不会起作用,一旦
loadShape()
给我一个PShape
,而不是一个Shape
How can I make loadShape
returns a Shape
? 如何使
loadShape
返回Shape
?
Thank you 谢谢
If loadShape()
returns a PShape
, then it returns a PShape
. 如果
loadShape()
返回PShape
,则返回PShape
。 You can't make it return a subclass of PShape
. 您不能使其返回
PShape
的子类。
Easiest approach would be Shape
either copies the PShape
into a new instance: eg 最简单的方法是
Shape
将PShape
复制到新实例中:
Shape myLoadShape(String filename)
{
return new Shape(loadShape(filename));
// Assumes you have a `Shape(PShape)` constructor.
}
or perhaps Shape
isn't a subclass, but it contains a PShape
data member. 或者
Shape
不是子类,但是它包含一个PShape
数据成员。
class Shape
{
// No one picked up my C++ syntax goof ;-)
protected PShape pshape;
// Using a constructor is just one way to do it.
// A factory pattern may work or even just empty constructor and a
// load() method.
public Shape(String filename)
{
pshape = loadShape(filename);
// Add any Shape specific setup
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.