javaabstract-methods

Cloning an implemented abstract method


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

Solution

  • 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();