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
?
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.
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.