Object slicing in Java

9.5k views Asked by At

Can you take a subclass object and somehow convert it to an object of the same type as the parent class and at the same time slicing all the fields that are not part of the parent class?

I know you can do this in C++, but I have no idea how to do it in Java.

5

There are 5 answers

1
miorel On BEST ANSWER

Try this:

class Parent {
    private int fieldA;

    Parent(int fieldA) {
        this.fieldA = fieldA;
    }

    Parent(Parent object) {
        this.fieldA = object.fieldA;
    }
}

class Child extends Parent {
    private int fieldB;

    Child(int fieldA, int fieldB) {
        super(fieldA);
        this.fieldB = fieldB;
    }
}

Then you can do something like Parent parent = new Parent(child); and you will achieve the desired result, but as others commented this won't be a conversion but rather construct an entirely new object.

8
Tom Hawtin - tackline On

You cannot change the runtime type of an object in Java (though you can assign a reference to and object to a supertype, and cast back to a subtype). You would need to construct a new object of the superclass runtime type.

I would generally recommend that all classes should be abstract or leaf (conceptually final, if not actually marked as such for pragmatic reasons).

0
quamrana On

There is no direct analog of slicing in Java, but I'm sure you can simulate this by adding a member function to either the parent or child that will create a new parent instance for you.

3
RubyDubee On

I haven't seen type-slicing in Java. And i don't think there's much need of it...

You can anytime do this in Java

Object x = new String("hello");

Here you will not have all the functions that String class provides

3
John Kane On

Im not sure why you want to do this, but you could have two classes implement the same interface, then reference the objects by the interface. For example:

class A implements something...
class B implements something...

something = new A();    
something = new B();