How do you know if an explicit object casting is needed

通俗来讲,不可能将一只是猫的动物强转为狗
再说Graphics2D:

 

import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class MainClass {
	public static void main(String[] args) {
		JFrame jf = new JFrame("Demo");
		Container cp = jf.getContentPane();
		MyCanvas tl = new MyCanvas();
		cp.add(tl);
		jf.setSize(300, 200);
		jf.setVisible(true);
	}
}

class MyCanvas extends JComponent {
	public void paint(Graphics g) {
		Graphics2D g2 = (Graphics2D) g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		Font font = new Font("Serif", Font.PLAIN, 96);
		g2.setFont(font);

		g2.drawString("jade", 40, 120);
	}
}

 

g之所以能强转为Graphics2D,多是因为它的运行时实例应是两者(Graphics,Graphics2D)的共同子类,当然Graphics2D本身是Graphics的子类,这里就像将一只是猫的动物强转为四脚兽

只有强转后,方可调用自Graphics2D特有的方法如setRenderingHint

另外一点只有向下转型才需强转(explicit casting),向上转型是自动完成的,比如当你将一个子类对象赋给一个父类型变量时。

 

from: http://topic.csdn.net/u/20110223/22/a00f64a0-c7ba-47fa-a4b1-4a703cc66df2.html?seed=1767655541&r=71791492#r_71791492

你可能感兴趣的:(java,html,.net,swing)