We help IT Professionals succeed at work.

upcasting down casting object remains same but refernece changes

Hi,

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

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?

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.