Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading