The downward transformation of java

java rookie, read java Core Technology introduction Graphics2D class is a subclass of Graphics, in which there is a code
public void paintComponent (Graphics g) {

Graphics2D g2 = (Graphics2D) g
......

}
will there be no error in the downward transition here?

Mar.21,2021

public class test{
    public static void main(String[] args) {
        Graohics g = new Graphics2D();
        Graphics2D g2;
        if(g instanceof Graphics2D)
            g2 =  (Graphics2D) g;
        else
            System.out.print("error");
    }
}

class Graohics{

}

class Graphics2D extends Graohics{

}
output:()
public class test{
    public static void main(String[] args) {
        Graohics g = new Graphics();
        Graphics2D g2 =  (Graphics2D) g;
    }
}
java test
Exception in thread "main" java.lang.ClassCastException: Graohics cannot be cast to Graphics2D
    at test.main(test.java:5)

if the object you pass in is a Graphics2D, there will be no error.

Menu