Skip to content Skip to sidebar Skip to footer

Cloning An Instantiated Abstract Class

Instantiate an abstract class. -> Duplicate it, preserving the implementation of the abstract method. public abstract class Foo{… public int myVar; public abstr

Solution 1:

You could use clone. The use of this method is widely discouraged, but it does work.

For example:

publicabstractclassFooimplementsCloneable {

    privateint a;
    private String b;

    publicFoo(int a, String b) {
        this.a = a;
        this.b = b;
    } 

    publicabstractvoidrun();

    publicintgetA() { return a; }

    public String getB() { return b; }

    @Override
    public final Foo clone() {
        try {
            return (Foo) super.clone();
        } catch (CloneNotSupportedException e) {
            thrownew AssertionError(); // Can't happen
        }
    }
}

Then, you can do:

Foo original = new Foo(3, "bar") {
    @Override
    public void run() {
        System.out.println("Hello, world!");
    }
};
Foo copy = original.clone();
System.out.println(copy.getA());
System.out.println(copy.getB());
copy.run();
System.out.println(copy == original);

The output is:

3
bar
Hello, world!
false

An alternative is to use Serializable.

publicabstractclassFooimplementsSerializable {

    privateint a;
    private String b;

    publicFoo(int a, String b) {
        this.a = a;
        this.b = b;
    }

    publicabstractvoidrun();

    publicintgetA() { return a; }

    public String getB() { return b; }

    public final Foo copy() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            new ObjectOutputStream(baos).writeObject(this);
            return (Foo) new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())).readObject();
        } catch (Exception e) {
            thrownew AssertionError(); 
        }
    }
}

With this version, replace clone by copy and you'll get the same result.

Solution 2:

You can do this...

publicclassTestFooextendsFoo{

    privatestaticStringTAG = TestFoo.class.getSimpleName();

    @Overridepublicvoiddo(){
        Log.i(getTag() , “this is a special Foo”); //executable process
    }

    protectedStringgetTag(){
        returnTAG;
    }
}

And then instantiate TestFoo objects that will perform do(). If you want a separate Tag for each instance you can override the getTag() function in the instanted class. Not sure if this is what you need but a lot easier to explain than a comment :P

NOTE

If this is something you would be doing in a lot of places, and you don't want to subclass all over the place (mentioned in the comments) please look at Paul Boddington's answer, particularly the copy portion.

Post a Comment for "Cloning An Instantiated Abstract Class"