Can someone help me understand what is happening in this code?
public class unaClase extends Applet{
public void paint(Graphics g){
g.drawRect(0, 0, 400, 200);
}
}
In my understanding it is something like that I create a class named aClass that inherits (because it becomes a child ) methods and attributes of the Applet class ; then it overrides the paint method (which was inherited from Applet ) and this method expects to receive an object (which we named g ) created from the Graphics class and then we call the drawRect method that is proper to the object g (which was created from the Graphics class ); so that when the class aClass is executed a rectangle is drawn , is it so?
A lot really happens in that code even if it doesn't look like it.
This line creates a data type called
unaClase
, which inherits all the characteristics and methods of a parent class called ,java.applet.Applet
which in turn inherits characteristics of a class calledjava.awt.Panel
, which in turn inherits from a class calledjava.awt.Container
, which in turn inherits from a class calledjava.awt.Component
that inherits fromjava.lang.Object
(Object for the mates).So to create an instance of type
unaClase
, you must first create all of the parents so that you can pass their property and method references to it.In the case of
you are redefining the functionality of a method that comes from the class
java.awt.Container
, which receives an object of typejava.awt.Graphics
that is wonderful in itself, since it contains the information of your graphical context and the references to native methods of your operating system to perform the painting routines and detection, which is why when callingyou delegate to that class the task of modifying the graphical context to add a rectangle with the color it already detected.
That graphic context is something very important, since it can be a CRT, an LED screen, or even something more abstract such as a web browser, and for all cases the same code works; that is the power of abstraction.
Something I want to point out is that your Applet is part of the
Abstract Web Toolkit
or AWT, and at no time in your code did you use Swing. Swing has its own specialization called JApplet specially optimized to work with Swing.Another way to use an Applet today is to use the JMainFrame class, which is responsible for putting a Wrapper on it to embed it in a frame.