Unhandled Exception Unhandled Exception - 2 years ago 73
Java Question

What is the top level component passed to the paint() call?

Reviewing some tutorials related to Java and graphics and constantly seeing the following :

public void paint (Graphics g)
Graphics2D g2;
g2 = (Graphics2D) g;

Both Graphics and Graphics2D are abstract classes.
Plus, Graphics2D is a subclass of Graphics.
As a result, the cast from Graphics to Graphics2D (g2 = (Graphics2D) g;) shouldn't work, right?

public class Object1 {
int obj1Var1;
public void obj1_Method1()
System.out.println("Inside Object1:Method1");

public class Object2 extends Object1{
int obj2var1;
public void obj2_Method1()
System.out.println("Inside Object2:Method1");

Using the above, which is sort of a parallel with the Graphics / Graphics2D scenario shows that it fails using the following.

Object1 obj = new Object1();
Object2 obj2 = (Object2)obj; <----This fails as expected.

Since the cast from Graphics to Graphics2D works (especially since they are abstract objects) then the original object in memory must already be a Graphics2D and defines the abstract methods. So, which is the actual underlying object in memory that is being referenced by the Graphics object being passed to the paint() call?

Answer Source

In Oracle JDK, the class is called sun.java2d.SunGraphics2D. You can run this program to see what it is in your version of Java:

import java.awt.Graphics;
import javax.swing.JFrame;

public class SwingTest {
    private static class Frame extends JFrame {
        public void paint(Graphics g) {

    public static void main(String[] args) {
        Frame frame = new Frame();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download