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?
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.