Search code examples
javamethodscastinggraphics2d

Am I getting Java and JavaScript (ECMA-262) mixed up?


I'm new to Java and JavaScript. While working though some Java Tutorials, I got to the part about casting:

public void paint (Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    ...
}

Is the component method paint casting a Graphics object g onto an Object class {} or am I getting this idea mixed up with JavaScript where a function is an Object?

function Graphics() {this.type = 'graphics object'};
var g = new Graphics();
g.type;
//"graphics object"
Graphics.prototype.g2d = 'g2d object';
g.type;
//"graphics object"
g.g2d;
//"g2d object"

When paint(g) is called, is it adding Graphics attributes to {} and then adding Graphics2D attributes to Graphics?

EDIT: From the Java Tutorials

To employ Java 2D API features in the application, cast the Graphics object passed into a component’s rendering method to a Graphics2D object.

When is says cast Graphics to Graphics2D is g changing by adding extra attributes and then referring to it thereafter as g2?


Solution

  • I'm not sure what you're referencing about JavaScript but the first code segment is casting a Graphics object to a Graphics2D object.

    The object is not changing. Java, unlike JavaScript is strongly typed. So g was a Graphics2D object the whole time. Casting just lets the compiler know that it is one.

    Also, you can't add attributes to functions in Java.