I am sometimes credited with perfect pitch. I'm personally unconvinced... but if I can hum a song I can usually work out the top notes of the melody line by comparing the notes to the upper limit of my vocal range.
I know what it feels like when I sing a G or A and so I can use this to establish the melody line notes and then work "down" to get the bass. After that working out the key is just a bit more relative pitch comparison but also using knowledge of the way chords sound in an ensemble, especially when the bass is NOT the root or fifth, and the chord is NOT pure (e.g. diminished, suspended , augmented, added 7's 9's 11' etc).
Or to summarise
Practice.
_________________________
John Allcock