Are there any alternatives to implementing Clone in Java?

前端 未结 5 1163
醉酒成梦
醉酒成梦 2021-01-12 15:10

In my Java project, I have a vector of various types of Traders. These different types of traders are subclasses of the Trader class. Right now, I have a method that takes a

5条回答
  •  囚心锁ツ
    2021-01-12 15:35

    Just add an abstract copy method. You can use covariant return types so that the derived type is specified to return a derived instance, which may or may not be important.

    public interface Trader {
        Trader copyTrader();
        ...
    }
    
    
    public final class MyTrader implements Trader {
        MyTrader copyTrader() {
            return new MyTrader(this);
        }
        ...
    }
    

    Sometimes you might want to generically deal with a collection of derived type of Trader that needs to clone and then return the a properly typed collection. For that you can use generics in an idiomatic way:

    public interface Trader {
        THIS copyTrader();
        ...
    }
    
    
    public final class MyTrader implements Trader {
        public MyTrader copyTrader() {
            return new MyTrader(this);
        }
        ...
    }
    

提交回复
热议问题