why is there not a Runtime error when assigning Graphics reference to Graphics2D reference variable in paintComponent method?

StackOverflow https://stackoverflow.com/questions/23535526

  •  17-07-2023
  •  | 
  •  

Question

I know that the assignment Below gives a Runtime error and i know why:

Sub sb = (Sub) new Super();

public class Super {
    //class  members
}



public class Sub extends Super{
     //class members
}

But why is there not a RuntimeError, when we override the protected void paintComponent(Graphics g) method of javax.swng.JPanel (after all Graphics2D extends Graphics ):

Graphics2D g2d = (Graphics2D)g;

is it because g already has a Graphics2D reference in it?

Was it helpful?

Solution

That isn't an error because, as your say, g is really a Graphics2D object instantiated by system (keep in ming Graphics2D is a subclass of Graphics).

When you do:

Sub sb = (Sub) new Super();

you are explicity creating a new object of the superclass. However, when you do:

Graphics2D g2d = (Graphics2D)g;

you are not creating new Graphics2D object, but casting an existing object which is already a Graphics2D instance.

In the case of swing rendering, the object to perform graphics operations is a Graphics2D object, but paintComponent() receive a Graphics object for backward compatibility.

OTHER TIPS

There is no runtime error because it's not the same to what you're doing in your method what happens here is more like this:

public void doSomethingWithSuper(Super superObj) {
    superObj.methodOfSuper();
}

public void doSomethinfWithSubThatCanResultInException(Super superObj) {
    Sub sub = (Sub) superObj;
    sub.methodOdSub();
}

Super subObj = new Sub();
Super superObj = new Super();

doSomethingWithSuper(subObj); //ok
doSomethingWithSuper(superObj); //ok

doSomethinfWithSubThatCanResultInException(subObj); // ok because the dynamic type of subObj is Sub therefore the cast is valid
doSomethinfWithSubThatCanResultInException(superObj); // exception because the dynamic type of superObj is super therefore the cast is not valid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top