-2

Why does MyCanvas(VisualizerProvider listener) have a parameter of type VisualizerProvider listener while the interface is defined below, and the class has not been initialized yet?

import java.awt.Canvas;
import java.awt.Graphics;

/**
 *
 * @author ACER
 */
public class MyCanvas extends Canvas{
    public static final long serialVersionUID = 2L;
    
    private VisualizerProvider listener;
    
    public MyCanvas(VisualizerProvider listener){
        super();
        this.listener = listener;
    }
    
    @Override
    public void paint(Graphics g){
        super.paint(g);
        clear(g);
        listener.onDrawArray();
    }
    
    public void clear(Graphics g){
        g.setColor(ColorManager.CANVAS_BACKGROUND);
        g.fillRect(0,0, getWidth(), getHeight());
    }
    
    public interface VisualizerProvider{
        void onDrawArray();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • The interface may be *nested* in the class, it is separate and does not rely on an **instance** of that class (i.e. it is not an *inner* class, which requires an instance of its parent). This is just a form of code organization, and it would work exactly the same if `VisualizerProvider` had been a top-level interface in its own file (other than that its name would then not contain `MyCanvas`). – Mark Rotteveel Aug 11 '23 at 10:28

0 Answers0