With casting no object conversion or transformation of any kind is happening.
Just imagine you have the following class structure:
class Mammal { }
class Human extends Mammal { }
class Dog extends Mammal { }
Now when you create a new instance of Human with Human human = new Human();
that will also be a Mammal, right? So you could write a method like:
public void doSoemthing(Mammal mammal) {
if (mammal instanceof Human) {
Human human = (Human) mammal;
human.doWork();
} else if (mammal instanceof Dog) {
Dog dog = (Dog) mammal;
dog.bark();
}
}
and invoke the method like:
doSomething(new Human());
So your method can take any type of Mammal as an input parameter and in your method you can check what kind of Mammal it really is. So when you pass a new Human()
as the input, the object's actual type will be Human. The reason because you can pass a Human to a method expecting a Mammal is because inheritance. So what your method will know is that the input parameter is definitely a Mammal. But it can be any kind of Mammal. If you want to know what the Object's actual type is you can use instanceof
for example. And in this line:
Human human = (Human) mammal;
doesn't mean you are converting the mammal input parameter. It just means that from now on you want to use the input parameter as a Human. And you can do that, because with the isntanceof you check that it's really a Human. You could also do something like this:
public void doExample2(Object input) {
if (input instanceof Integer) {
System.out.println("I am a number");
} else if (input instanceof Graphics) {
System.out.println("I am a Graphics");
}
}
Notice the type of teh input parameter. Object is the base class of everything.
So getting back to your scenario. You do that casting, because from the context of your application the input parameter will always be a Graphics2D, and that's why you can do that casting, and also to use the methods provided by Graphics2D.