Why can I cast an object? Can it be done with other objects?

ErlichBachman :

So I was writing a paintComponent(Graphics g) method and I realized at the beginning that I am casting it to Graphics2D g2 = (Graphics2D) g;. I wrote this code a while ago and just realized I have no clue what this is. I googled a bit but object casting is a bit foreign to me.

One object reference can be typecast into another object reference. This is called casting object.

^^Word for word from my textbook by Y. Daniel Liang

I don't understand why this works. Graphics and Graphics2D are two different objects how could they inherit instance variables and methods from each-other? Obviously I am aware of primitive casting ie widening and narrowing. That makes sense since they are just wrapper classes of Integer, Double, Byte etc...

dfritsi :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416231&siteId=1