Why were medieval castles built?

Medieval Castles were built for many purposes, but by far the most common purpose was that of defense. A Castle was a difficult structure to get past, even after the introduction of primitive gunpowder weapons and complex siege weapons. They also preserved the king's and nobles' power over the land.