upcasting down casting object remains same but refernece changes

gudii9
gudii9 used Ask the Experts™
on
Hi,

When we do upcasting down casting and object instance why actual object still remains same but referenece changes? please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
CPColinSenior Java Architect

Commented:
Please link to where you read that.

Author

Commented:
public class Casting {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Derived drv = new Derived();

		Base base = (Base) drv;

		System.out.println("Class : " + base.getClass()); 

		
	}

}

Open in new window


public class Derived extends Base{

}

Open in new window


public class Base{

}

Open in new window


output is
Class : class Derived
i expected Base??
CPColinSenior Java Architect

Commented:
i expected Base?
Why?
Should you be charging more for IT Services?

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

Commented:
package com.upcast;
class Base {
    public Base() {}
    public void foo() {
        System.out.println("I'm the base!");
    }
}

Open in new window

package com.upcast;

class Child extends Base {
    public Child() {}
    public void foo() {
        System.out.println("I'm the child!");
    }
}

Open in new window


package com.upcast;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Child x = new Child();
		Base y = (Base) x;
		y.foo();
	}

}

Open in new window

output
I'm the child!
i expected I'm the base! (as reference is Base type)

Author

Commented:
i expected Base?
Why?

since we upcaste to Base from Derived?
Senior Java Architect
Commented:
Casting does not change the type of an object. It only changes the type of the reference to it. No matter how much casting you do to an object, calling getClass() on it will return the same class.

Author

Commented:
is it same with down casting? any good  example on down casting? do we do down casting also often as upcasting?
CPColinSenior Java Architect

Commented:
It's the same with any casting.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial