• Post Reply Bookmark Topic Watch Topic
  • New Topic

Prevent cloning in subclasses  RSS feed

 
Sudipto Ghosh
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a class implements Cloneable interface and overrides clone() method to enable itself for cloning, how a subclass of it can prevent cloning if the subclass is not interested in cloning?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Override the clone() method and have it throw a CloneNotSupportedException.
 
Sudipto Ghosh
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick reply. I could not get your answer properly !!
My superclass implementation of the clone() method doesn't throw any exception rather it consumes it. In this scenario, without changing my superclass implementation how can I prevent the cloning of my subclass.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, then you'd have to throw a RuntimeException of some kind with an explanatory message. Note, though, that you need to think a bit about why you're doing this. If class A can be cloned, and B is a subclass, then it's reasonable to expect B to be cloneable too. Since it's not, B isn't really a kind-of A, is it? This is a violation of the "Liskov Substitution Principle" (LSP) which some folks believe it a good litmus test for inheritance. Are you sure B should extend A? Maybe B should simply contain an instance of A and forward some method calls to it. Is there an interface that A implements that B can implement this way by delegation?
 
Sudipto Ghosh
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ernest !! I think I got the answer. This was a question which was asked to me ! To add on to this, I got to know about "Liskov Substitution Principle" !
Thank you !!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!