'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 1:[1]
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
Solution 2:[2]
Try this:
ClassA objB = objA.getClass().newInstance();
objB.method();
No Cloneable needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | frascu |
| Solution 2 | Ralf Renz |
