How did the appearance of a medieval city resemble a castle? How can this be explained?

The cities were surrounded by powerful walls with towers; the city had a town hall resembling a donjon.
This was necessary to protect the urban population from enemy raids, from robbers.

Remember: The process of learning a person lasts a lifetime. The value of the same knowledge for different people may be different, it is determined by their individual characteristics and needs. Therefore, knowledge is always needed at any age and position.