Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When casting a derived class to a parent class do you lose data?

Tags:

java

For example

public class parentClass{
     //stuff done
 }

public class derivedClass extends parentClass{
    // has data that parentClass does not
}

// some function 
public parentClass foo(parentClass myVar){
    return myVar
}

// ... later ...

{
  ...
   derivedClass dClass1 = new derivedClass();

   parentClass pClass = foo(dClass1);

   derivedClass dClass2 = (derivedClass)pClass;
 ...
}

Was data lost between dClass1 and dClass2? I am not sure, I think the answer is no. I know that if I was using doubles and ints then data IS lost, but that isn't using pointers and objects, so I wasn't sure.

like image 329
njfife Avatar asked Sep 19 '13 18:09

njfife


1 Answers

You cant cast objects so you can't lose data. All you can do is cast the reference to an object and this doesn't alter it in any way.

like image 117
Peter Lawrey Avatar answered Nov 13 '22 15:11

Peter Lawrey