Search code examples
javaoopapplet

What happens in this code snippet with the Applet class?


Can someone help me understand what is happening in this code?

public class aClass extends Applet{
    public void paint(Graphics g){
        g.drawRect(0, 0, 400, 200);
    }
}

My understanding is this, I create a class of name aClass that inherit(because it becomes a daughter) methods and attributes of the Applet class; then overwrites the paint method(which had been inherited from Applet), and this method expects an object as a parameter (which we put name g) created from the class Graphics, and then we call the drawRect method that is proper to the g object (which was created from the Graphics class); so that when the aClase class is executed, a rectangle is drawn, is it like that?


Solution

  • Applets are an old, deprecated technology and you should consider newer technologies such as Java Web Start. That said, your understanding is mostly correct apart from some of the terminology.

    I create a class of name aClass that inherit(because it becomes a daughter) methods and attributes of the Applet class;

    Extending a class means that you create a new sub-class (in this case aClass) which is based off of the public contract and private implementation of the super class (Applet). The way that aClass behaves should respect the Liskov substitution principle at a high level meaning that anywhere you can use an Applet, you should be able to use an aClass too. This means respecting the public contract of Applet in aClass.

    Applet class; then overwrites the paint method(which had been inherited from Applet),

    Partially correct. aClass will override paint meaning that it will called when invoking paint on an instance of aClass rather than the default definition in Applet. It does not overwrite, as it is still possible to call the super implementation of this method. You should also annotate overriden method with the @Override annotation

    @Override
    public void paint(Graphics g){
        // calls paint from higher up the inheritance tree
        super.paint(g); 
        g.drawRect(0, 0, 400, 200);
    }
    

    this method expects an object as a parameter (which we put name g) created from the class Graphics,

    Yes, or just like aClass extends Applet, this could be some class that also extends Graphics.

    e.g. class FooGraphics extends Graphics { ... }

    and then we call the drawRect method that is proper to the g object (which was created from the Graphics class);

    Yup. Part of the public contract to the Graphics class.

    so that when the aClase class is executed, a rectangle is drawn, is it like that?

    Whenever the Applet framework decides to update the view it will call this method which has the effect of drawing a rectangle.