Q:

cast Object and call methods - from unrelated classes

I am using the Processing.org api - so i cant just change the classes in question.
Problem is simple, but i havent found an answer:
void drawStuff(PGraphics view) {
    view.beginShape();
    view.vertex(... lots of vertex calls / lines
}

void drawStuff(PShape view) {
    view.beginShape();
    view.vertex(... lots of vertex calls / lines
}

what i need is a way to combine them into one method, like:
void drawStuff(Object view) {
    // how to cast to PShape and PGraphics
    view.beginShape();
    view.vertex(... lots of vertex calls /lines
}

the classes PShape and PGraphics have same/similar methods, at lest for the one i call, they are the same. But according to the Processing javadocs, PShape and PGraphics are both coming from java.lang.Object, so as far as i understand the dont share anything.

A:

Like others pointed out in the comments of the OP, write a wrapper class/interface. The interface is the abstraction towards your code in which you don't want to know the actual implementation you're dealing with:
Start with defining the interface:
public interface PWrapper {
    public void beginShape();
    public void vertex();
}

Then, because of the unfortunate design in which PShape and PGraphics have nothing in common but Object, you'll need to implement a wrapper for each of these classes that implements your new interface. These wrappers are infact delegating their method calls to the appropriate methods of the wrapped object. For example, the wrapper for a PShape would be implemented like this:
public final class PShapeWrapper implements PWrapper {

    private final PShape ps;

    public PShapeWrapper (PShape ps){
        this.ps = ps;
    }

    @Override
    public void beginShape(){
        ps.beginShape();
    }

    @Override
    public void vertex(){
        ps.vertex();
    }
}

Then again in your code, define the method like this:
void drawStuff(PWrapper wrap) {
    wrap.beginShape();
    wrap.vertex();
}

As you can see, this method does not know what runtime object it's dealing with: it may be a PShapeWrapper (see above) or a PGraphicsWrapper (not posted). Even better: it may be any class that implements PWrapper but doesn't exist yet, so this is a maintainability plus.
This design pattern is called "Adapter".

