简体   繁体   中英

How can I add method to an existing object in Java?

I'm using a Processing library to build my project in Java. I use a function that returns me an object of type PShape (which I don't have access to source).

I need to make this object of type Shape (a class I designed that extends 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.

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

How can I make loadShape returns a Shape ?

Thank you

If loadShape() returns a PShape , then it returns a PShape . You can't make it return a subclass of PShape .

Easiest approach would be Shape either copies the PShape into a new instance: eg

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.

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
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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