cloneable interface

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • virus
    New Member
    • Nov 2006
    • 9

    cloneable interface

    Hello, I am new to java. i want to know how the clneable interface works?
    clone merhod belongs to Object class. As far as i know every class implicitly extends Object class. why i vw to implement cloneable interface to call the clone method? please clear my doubts....
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by virus
    Hello, I am new to java. i want to know how the clneable interface works?
    clone merhod belongs to Object class. As far as i know every class implicitly extends Object class. why i vw to implement cloneable interface to call the clone method? please clear my doubts....
    Read the first 4 lines of the API specs for it.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Sometimes you don't want objects of your class to be cloneable (think of
      singletons). The clone() method checks whether or not your class (or a parent
      of it) implements the Cloneable interface. If it does it clones your object. If it
      doesn't it throws an Exception. It's just a safety measure.

      kind regards,

      Jos

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Darn, too slow again ...

        kind regards,

        Jos ;-)

        Comment

        • BigDaddyLH
          Recognized Expert Top Contributor
          • Dec 2007
          • 1216

          #5
          This chapter from "Effective Java" has an excellent discussion of several overridable Object methods, including clone. It's required reading!

          Comment

          • destiny23
            New Member
            • Mar 2008
            • 1

            #6
            The simple reason why one cannot directly use Object.clone() method without implementing Cloneable interface is that Object.clone is a protected method.

            Comment

            • BigDaddyLH
              Recognized Expert Top Contributor
              • Dec 2007
              • 1216

              #7
              Originally posted by destiny23
              The simple reason why one cannot directly use Object.clone() method without implementing Cloneable interface is that Object.clone is a protected method.
              While that's true, in order to implement a proper cloning strategy one should read that article!

              Comment

              Working...