Avatar of gudii9
gudii9
Flag for United States of America asked on

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
JavaJava EEProgrammingProgramming Languages-OtherProgramming Theory

Avatar of undefined
Last Comment
CPColin

8/22/2022 - Mon
CPColin

Please link to where you read that.
gudii9

ASKER
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??
CPColin

i expected Base?
Why?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
gudii9

ASKER
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)
gudii9

ASKER
i expected Base?
Why?

since we upcaste to Base from Derived?
ASKER CERTIFIED SOLUTION
CPColin

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
gudii9

ASKER
is it same with down casting? any good  example on down casting? do we do down casting also often as upcasting?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CPColin

It's the same with any casting.