tags:

views:

35

answers:

3

Yes, I know we can upcast or downcast in Java. But the type of the instance doesn't really seems to be change and it's giving me a problem.

E.g. class Foo{ int a, b; .. constructers, getters and setters }

class FooDTO extends Foo { ... }

FooDTO dto = FooDTO(1,2); Foo parent = (Foo) dto;

in hibernate, when saving the "parent", it's still think that it's a DTO object and can't be saved. Can I really turn a child instance into a parent instance?

A: 

Hi,

No u can't trun child into parent in this way. You have create the object for parent sperately.like, Foo parent new Foo(dto.getA(),dto.getB());

Jothi
A: 

you can save the 'parent' by using hibernate's save(entityName, object) method. In this case the entityName is the fully qualified class name of 'parent'.

Salandur
A: 

An object's type cannot be changed after it has been created. If you create a FooDTO object it will always be a FooDTO object.

When you cast you are telling the JVM that you are going to use a reference of type X to point at an object that you know is of type X.

class Parent {}
class Child extends Parent {}

class Test {
    public void stuff() {
        Parent p = new Parent(); // Parent reference, Parent object
        Parent p2 = new Child(); // Parent reference, Child object
        Child c = new Child();   // Child reference, Child object 


        Parent p2 = c; // no explicit cast required as you are up-casting
        Child c2 = (Child)p; // explicit cast required as you are down-casting. Throws ClassCastException as p does not point at a Child object
        Child c3 = (Child)p2; // explicit cast required as you are down-casting. Runs fine as p2 is pointong at a Child object
        String s1 = (String)p; // Does not compile as the compiler knows there is no way a Parent reference could be pointing at a String object            

    }
}
dairemac