Castles in Spain were built mainly for defensive purposes. During the Middle Ages, northern Christian kingdoms had to secure their borders with their Muslim southern neighbours, thus forcing both Christian and Muslim kings to grant border fiefs to their liege noblemen so as to keep and maintain defensive fortresses. When the Reconquista advanced, those border castles lost their initial purpose, and, as in the rest of medieval Europe, they were used as noble residences and fief-keeps. However, due to sporadic threats of war, they kept their military purposes, for enemy invasions were common. In some locations, such as the Basque country, fiefdoms did not exist as such, and noble families could not afford nor did they need huge fortresses, giving rise to many tower houses. On the other hand, in Muslim Spain many castle-palaces were built: the petty taifa kingdoms that arose after the fall of the Caliphate of Córdoba were militarily weak but culturally rich, and every emir or king liked magnificent palaces, of which the Alhambra of Granada is an example. During the late Middle Ages, Christian kingdoms had secured and enriched themselves well enough to support a more courtly lifestyle, so more residential castles were built, such as the Alcázar of Segovia, which was used as the main residence of the kings of Castile, whereas the Castle of Olite, built in a luxurious gothic style, was the seat of the Kingdom of Navarre's royal court.
After the Conquest of Granada in 1492, the Catholic monarchs ordered all the castles in their realms to be handed over to the Crown. Although the order was not completely carried out, the War of the Germanias, a rebellion against king Charles V in the early 16th century, forced the new Spanish Habsburg dynasty to continue the process, and many castles were demolished as well. Most of castles in Spain were successively abandoned and dismantled, Spanish kings fearing noble and peasant revolts, especially in the newly conquered lands. Accordingly, most of them are nowadays in a state of decay, and although some restoration work has been done, the number of former castles is so large that the Spanish government lacks both the resources and the will to restore them all.
Nowadays in Spain there are around 2500 castles corresponding only to this kind of fortification.