It's up to the performer/listener to relate the music to their own stories, feelings, characters, etc. The generic titles like sonata show that they adhere to a specific form, but not a specific story.
Music in the Classical period began having multiple emotions, feelings, characters in each piece rather than one "affect" like in the Baroque period. Think of a Mozart sonata that has different themes and motives throughout, compared with a Bach prelude or dance that is pretty much one mood throughout. Of course, Baroque pieces had generic titles, too!
Others are correct that "moonlight" was just a nickname given by a critic who was describing the sonata 30 years later.