bob larry
bob larry

Reputation: 67

Java - How do you upcast and downcast the same object

Say we have two classes.

class Animal{/*code*/}
class Cat extends Animal{/*code*/}

From what I've been learned, upcasting and downcasting works like this

Cat c1 = new Cat();
Animal a = c1; //Upcasted to Animal
Cat c2 = (cat) a; //Downcasted back to Cat

But the only problem is, each time you upcast or downcast, you create a new Object. Is there anyway to upcast and downcast an object from Cat to Animal and back to Cat, so that only one object is being casted? For example

Cat c --> Animal c --> Cat c //Upcasted to Animal, and downcasted back to Cat, but done all on one object.

Thanks!

Upvotes: 2

Views: 414

Answers (2)

Joel.S
Joel.S

Reputation: 31

Only one object is being created in memory, and there are three references to this one object. Of note is that the reference of type Animal won't have access to anything specific to the Cat type. Read up on polymorphism if you want to know more.

An important thing to note here is that if you change anything in that object it will be reflected by any of the references. This is demonstrated below. Assume there is an abstract Animal class which has a name and appropriate getter & setter.

Note that even though the setName() is called on the cat variable, the name is still changed when calling getName() on animal.

        Cat cat = new Cat("foo");
        Animal animal = cat;
        System.out.println(animal.getName()); // foo
        cat.setName("bar");
        System.out.println(animal.getName()); // bar  <--  The name of animal changed when we changed cat1.

Upvotes: 2

Ivan
Ivan

Reputation: 8758

These 3 lines create only one object in heap and 3 references which point to the very same object

Cat c1 = new Cat(); //this is where object is created in heap
Animal a = c1; //Upcasted to Animal, only reference is created not new object
Cat c2 = (cat) a; //Downcasted back to Cat, only reference is created not new object

You can start debugger and check that those references point to the very same object.

Upvotes: 5

Related Questions