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
LVL 7
gudii9Asked:
Who is Participating?
 
CPColinConnect With a Mentor Senior Java ArchitectCommented:
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.
0
 
CPColinSenior Java ArchitectCommented:
Please link to where you read that.
0
 
gudii9Author 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??
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
CPColinSenior Java ArchitectCommented:
i expected Base?
Why?
0
 
gudii9Author 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)
0
 
gudii9Author Commented:
i expected Base?
Why?

since we upcaste to Base from Derived?
0
 
gudii9Author Commented:
is it same with down casting? any good  example on down casting? do we do down casting also often as upcasting?
0
 
CPColinSenior Java ArchitectCommented:
It's the same with any casting.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.