'Is there a way to "cut down" a Java object to a inherited class?
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
