Reputation: 143
So this is what I noticed in Java:
If I make a class:
class IntStorage
{
public int i;
public void setInt(int i) { this.i = i; }
public int getInt() { return i; }
}
And inherit it, and store other data:
class IntAndStringStorage : IntStorage
{
public String s;
public void setString(String s) { this.s = s; }
public String getString() { return s; }
}
And I do this:
IntAndStringStorage IandSstorage = new IntAndStringStorage();
IandSstorage.setString("Test");
IntStorage Istorage = (IntStorage)IandSstorage;
IntAndStorageStorage test = (IntAndStorageStorage)Istorage;
System.out.println(test.getString());
It's completely valid even though I casted it to a inherited class. Now I assume the info is still inside the object, so could I completely cast it to the inherited class without keeping the old info? I don't want the String
storage left over in my int
storage class.
Upvotes: 3
Views: 389
Reputation: 136122
The best way to do it in Java is to create a new IntStorage based on IntAndDataStorage instance int value.
IntStorage intStorage = new IntStorage(intAndSstorage.getInt());
assuming you added IntStorage(int) constructor to IntStorage. There will be no String leftovers.
Upvotes: 2
Reputation: 7719
Casts do not change an object in Java (unlike C#, casts in Java cannot be overloaded). Casts thus only change the [compile-time] type the object appears as - it is always entirely valid to cast the object back to the original type.
To "cut down" an object would require
Also, interfaces are generally a nicer way of exposing certain "views" than relying on base types.
Upvotes: 13