Immunity that develops after exposure to a disease-causing infectious microorganism or other foreign substance, such as following infection or vaccination.