The correct answer is - evolution.
The whales trace their ancestry to four-limbed animals that were terrestrial. These animals where living next to the water bodies. They saw an opportunity and lack of competition in some of them, and they started to use the water as a hunting field. As they were spending more and more time in water, they started developing features that would help them in that environment, like webbed feet, more muscular limbs for peddling, smaller ears, smoother fur... As the time was passing, the features of these animals were becoming more and more suited for the water, with the fur being totally lost, the outer ear as well, with the back limbs becoming joined for better swimming, and the front ones becoming flippers for better peddling. Eventually, what we know in the present as whales emerged from those adaptations and the evolutionary pressure that those animals where experiencing.