• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why some classes dont work, if an interface is not implemented  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An interface is used to provide a framework to a class. If an interface is not implemented, then class does not give an error.

Some interfaces don't even have any method in them e.g. Serializable and Cloneable interfaces don't have any method in them. But still, if these interfaces are not implemented, then clone() does not work. So how is clone() related to cloneable interface ?

If I create a custom interface which has no method in it, can I relate this interface with any method ? So same is the case with cloneable interface. In other words, why is cloneable related to clone() only and not to any other method ?

Please explain this.

Thanks
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cloneable and Serializable are called marker interfaces. Marker interfaces aren't used very often, but when they are, the code that expects the class to implement the interface will look something like this:



Marker interfaces are just a way to take an existing feature in the language and use it differently than it was intended to accomplish a goal that can't be met otherwise--or at least can't be met easily.

I think the introduction of Annotations in Java 1.5 pretty much eliminated the need for marker interfaces, but Cloneable and Serializable have been around forever and are heavily used, so they're not going away any time soon.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nirjari patel wrote:So how is clone() related to cloneable interface ?

In that specific instance, it's related because Object's clone() method ensures that whatever called it implements Cloneable; and if not, throws a CloneNotSupportedException.

The fact is that, as Jeff said, they're very rare - and arguably not even Object-Oriented, since they tend to create dispatch code based on type checking. But unfortunately the world isn't perfect and, at the time, they were probably the best compromise available.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!