Home > Software design >  Cloning an implemented abstract method
Cloning an implemented abstract method

Time:02-23

I'm a beginner in Java and I wanted to ask a question:

Is that possible to clone implemented abstract method body?

Example:

public abstract class ClassA{
  public abstract void method();
}

ClassA objA = new ClassA(){
  public void method(){
    System.out.println("Yay");
  }
}

//creating objB with the same method as in objA

objB.method();
Output: Yay

CodePudding user response:

Yes, you can.

Just implement Cloneable interface to ClassA class.

public abstract class ClassA implements Cloneable {
    public abstract void method();
    @Override
    public ClassA clone() {
        try {
            return (ClassA) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

Then you can do this.

ClassA objB = objA.clone();
objB.method();

CodePudding user response:

You have to define an implementation of the abstract class ClassA:

public class ClassAImpl extends ClassA {
    @Override
    public void method() {
        System.out.println("Yay");
    }
}

Then you can create the instances objA and objB:

public class ExampleClass {
    public static void main(String[] args) {
        ClassAImpl objA = new ClassAImpl();
        objA.method();
        ClassAImpl objB = new ClassAImpl();
        objB.method();
    }
}

Output:

Yay
Yay

CodePudding user response:

Try this:

        ClassA objB = objA.getClass().newInstance();
        objB.method();

No Cloneable needed.

  • Related