If you have a constant pain in your body, why does a greater pain or pleasure make you not feel the original pain?
I'm not sure if why is referring to the biological basis or the reasoning for why it is beneficial but I've briefly summarised both. If you'd like more detail just accept and ask again clarifying your exact interest in this broad question.
Pain is taken up through the spinothalamic pathway but at may opportunities it may be blocked. It may be blocked by other ascending pathways or by descending pathways. There are a number of structures involved in this including endorphins and Interneurones which are part of the gate control theory of pain. Basically ascending sensory information is blocked when other sensory information is more acute or more pertinent. This is important for survival e.g. when feeling a lion it is important not to feel pain. That same endorphin pathway is highjacked by drugs such as morphine.