我有一堂课:

public class Shape extends PShape{
    private String name;
    private PApplet drawer;
    public Shape(PApplet drawer, String name){
       //constructor
       this.drawer = drawer;
       this.name = name;
    }
}


如果我有

PShape s;


我会做

s = drawer.createShape();//return PShape


但是,PShape实际上并没有构造函数,只有一个返回PShape的createShape方法。

如果要扩展Shape,我将在PShape的构造函数中放入什么?

this = drawer.createShape();


那行得通吗?如果没有,我该如何初始化扩展了ShapePShape

最佳答案

除了提供的答案外,您还可以考虑选择composition instead of inheritance

基本上:您将创建一个包含PShape实例的类,而不是扩展PShape。像这样:

public class Shape{
    private PShape myShape;
    private String name;
    private PApplet drawer;
    public Shape(PApplet drawer, String name){
       //constructor
       this.drawer = drawer;
       this.name = name;
       myShape = drawer.createShape();
    }
}


然后,只要需要,您就可以使用该PShape实例。

07-26 04:58