user2348979
user2348979

Reputation: 143

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.

Upvotes: 3

Views: 389

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

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

user2246674
user2246674

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

  1. to create a new object (perhaps of a base type) with less information or;
  2. have a mutable object that throws out (i.e. assigns null/default values) to various "cut out" fields.

Also, interfaces are generally a nicer way of exposing certain "views" than relying on base types.

Upvotes: 13

Related Questions