I think there’s an example I’ve been able to better understand the overlap part of.
There is a superclass geometric figures, within this superclass I have a method of area calculation. From this superclass, subclasses, rectangle class, triangle class and so on will be created, each with its area calculation method with the modifier override
. When I create a geometric figure
Triangulo triangulo = new Triangulo();
Quadrado quadrado = new Quadrado();
FiguraGeometrica figuraGenerica = new FiguraGeometrica();
FiguraGeometrica figuraGeometrica1 = (FiguraGeometrica)triangulo;
FiguraGeometrica figuraGeometrica2 = (FiguraGeometrica)quadrado;
The area calculation method of the triangle is in figuraGeometrica1
, because this was superimposed on the present method but is not in figuraGeometrica2
, once the method superimposed on it is that of the square. Already in figuraGenerica
the method of calculation of area is the way of superclass.
In the matter of memory, when there is the casting operation, down or up, no changes are made to the object, a reference, a new pointer is created pointing to the same object and the compiler interprets only that which is present in the superclass, that is, everything that had in the subclass object still exists, is not copied, only a new pointer in the stack is added pointing to the same object, so the compiler can access the fields present only in the superclass, but all other information is still present.
For example, within the Square class there is an attribute that is diagonal value, but this attribute does not exist in the superclass:
FiguraGeometrica figuraGeometrica2 = (FiguraGeometrica)quadrado;
in upcasting, a figure referenceGeometrica2 is created and points to the square that is in the Heap.
When performing a downcasting
Quadrado quadrado2 = (Quadrado)FiguraGeometrica2;
a new pointer is done, and it points to the same place, only now the compiler is able to access the diagonal attribute, which was not erased, was there all the time, in the same reference.
In short, the methods when casting is performed are the methods of the class itself, unless an overlap has been made. Attributes do not disappear, remain in the same reference only can no longer be accessed.
I believe that’s it !!!