I'm trying to figure out why it is allowed to downcast a Graphics instance to a Graphics2D instance.
It's usually against the rules to downcast a reference type that isn't inheriting the target type.
In the graphic-oriented classes the hierarchy is like the following:
- Graphics is the superclass
- Graphics2D is the subclass of the superclass Graphics
When drawing something in Swing you override the paint() method - And if you're in need of 2D-drawing you downcast the automatically supplied Graphics instance from the paint() method to a Graphics2D instance:
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
}
But this is reverse? A Graphics instance is NOT inheriting a graphics2D instance - It's the Graphics2D instance that IS inheriting a Graphics instance when looking at the class-hierarchy!
Why is this allowed?