It comes down to the change in the speed of sound at the interface. The speed of sound in air is approximately 343 m/s. The speed of sound in a solid object is typically much, much higher because the stiffness is much higher. For example, copper is 3901 m/s, brick is 4176 m/s and there are many other materials you can look at for reference.
On the other hand, a near-vacuum has extremely few molecules to transmit the sound. This means sound does not travel very well through it and the speed of sound is much, much lower. Contrary to popular belief, it's not zero for all frequencies, but for many sounds they just don't travel very well without molecules to transmit them.
So we have two conditions. In the first, the wave is going from one medium to another where the speed of sound is higher (the solid object) and the second the wave is going from one medium to another where the speed of sound is lower (the near vacuum). An animation of these two effects can be seen at the bottom of this page.
You can see that the transmission to a lower wave speed results in a phase shift (the wave is weakened and inverts) while the transmission to the higher wave speed results in just an amplitude weakening. A mathematical treatment of waves crossing the boundaries is performed using Maxwell's Equations, but an electromagnetic wave and a sound wave obey the same (basic) governing equations.
The primary mechanism in both cases is that a wave impacting a surface generates a wave in the second material. That wave will leave at either a higher or lower speed than the incident wave. If the properties of both materials were identical, the wave would pass through and there would be no reflection (no echo).