It is thought that bacteria developed the ability to produce restriction enzymes naturally in order to protect the cell from an invading virus. A virus reproduces by hijacking the DNA synthesis of its host to manufacture its own DNA. Restriction enzymes cleave the foreign DNA so that the virus cannot replicate.
Restriction enzymes, or endonucleases, are produced by bacteria. They recognize very specific sequences of nucleotides on a DNA strand. For example, BamHI recognizes the GATCC sequence and cleaves the strand right before the G. The specificity of the enzymes makes them ideal candidates for use in genetic engineering of cells and gene recombination in labs.
Bacteria use restriction enzymes as defense against invading viruses. Viruses affect the host cells by hijacking the cell's metabolism to reproduce, killing the host cell in the process. A key step to reproduction of a virus is DNA replication of the viral DNA. Bacteria that contain restriction enzymes can cleave the viral DNA and destroy the invading virus. Bacterial DNA is methylated, which means that the DNA of the bacteria is tagged with several methyl groups. Methylation protects bacterial DNA from getting cleaved by its own restriction enzymes.