Object Casting, please help
I am learning Java for the first time, and the only problem I am having right now is understanding object casting. Here is a quick example that does not work and I do not understand why:
class A {
}
class B extends A {
}
class ObjectCaster {
public static void main(String[] arguments) {
A a = new A();
B b = (b)a;
}
}
This always results in an error for me. The reason I am really perplexed is that the book I am studying (Sams Teach Yourself Java in 21 Days) shows a code snippet that apparently works, and is done in the same fashion:
public void paintComponent(Graphics comp) {
super.paintComponent(comp);
Graphics2D comp2D = (Graphics2D)comp;
... // more code
}
I don't understand why Graphics2D comp2D = (Graphics2D)comp; would work, because I am doing the same thing in my first example of code. A is the superclass, like Graphics, and B is the subclass, like Graphics2D. I define an object of type A and pass it with a cast to the object of type B and it doesn't work. However doing so with a Graphics object to a Graphics2D object, which is the same thing to my understanding, apparently works. I just don't get why...they should both be doing the same thing essentially. Please help me understand this, I don't want to be confused about object casting when I finally get to a point in my Java programming that I need to take advantage of it. Thanks a lot everyone,
-Derek