Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interfaces with no body

 
zaeem masood ashar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why do we have interfaces such as "Serializable" which do not define any method?

------------------
SCJP2
 
Prithvi Raj
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
interfaces like "Serializable" , "cloneable" are empty interfaces that do not contain any methods, but are used for tagging other classes with properties indicated by the interface type.

 
zaeem masood ashar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What are those properties (that tag-along)and where are they mentioned....i mean physically.....(knowing what a Serializable interface connotates)?
thanks
 
Scott Palmer
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that the interface is implemented IS the tag.
It is just liek some sort of boolean property on the class that doesn't really take up data in the class. At least that's how I understand it.
E.g. For Serializable, if the serialization APIs can cast the Object to Serializable the they know it is ok to serialize the class. Because the APIs get a generic Object there is no data member they can check or method they can call unless EVERY class implemented that member/method. So interfaces are a usefull may of tagging.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It allows you to test a class easily for that property.
Using SingleThreadModel from servlets as an example, if a Servlet implements this Interface then only a single thread can access a Servlet at a time.
Now you can write some code like this:

So this is a pretty simple example, but it means that the class you wrote has an extra (boolean) property associated with it that can be tested without any properties or additional code or difficulty. Quick and easy flag to say 'this class is different'
Dave.
 
zaeem masood ashar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a bunch fellows !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic