Java – use generics to implement common methods in abstract classes
•
Java
Suppose I have this hierarchy:
public abstract class AbstractEntity implements Cloneable { ... public AbstractEntity clone() { Cloner cloner = new Cloner(); AbstractEntity cloned = cloner.deepClone(this); return cloned; } } public class EntityA extends AbstractEntity { ... }
That's good. I can do this:
EntityA e1 = new EntityA(); EntityA e2 = (EntityA) e1.clone();
But I have to do a manual type conversion Is there any way to use Java generics to make the clone () method return the actual type of the subclass?
thank you!
Solution
I don't think we need generic drugs You can declare the clone () method in an abstract class and override it to return subclasses in subclasses
package inheritance; public abstract class AbstractEntity { public abstract AbstractEntity clone(); } package inheritance; public class ClassA extends AbstractEntity { @Override public ClassA clone() { return null; } } package inheritance; public class Driver { /** * @param args */ public static void main(String[] args) { ClassA a = new ClassA(); ClassA b = a.clone(); System.out.println("all done"); } }
Isn't that what you want to do?
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码