First of all, let's leave the cosmic objects aside for a moment and let's talk a bit about gravity. The gravitational force has been the first elementary force to be fully understood by physicists, however, what physical phenomena causes it remains mostly a mystery even today. Furthermore, this inability to understand gravity seems to affect the way how we understand the structure, origins and the inevitable end of the universe. Gravity is the force of attraction exerted between objects. This causes them to pull themselves together in order to form even larger structures, such as the Sun and the Earth.
As matter is pulled towards the object, it is ultimately forced to take a particular shape, depending
on how malleable the substance that the object is made of is. A cube of steel, for example, will not take the shape of a glass in normal Earth conditions of pressure and temperature even in a million years, while water, on the other hand, along with other liquids do. Nevertheless, when in a 'gravity-free' environment, all objects tend to take a spherical shape. But why is that? If you think about it really hard, you might realize that you've reached the same conclusion mathematicians reached a long time ago. The sphere is the geometrical shape which has the smallest surface area related to the volume it contains.
When in space, the gravitational component of an orbiting object has a direction tangential to the surface of the Earth, determining a freefall towards the surface in a sideways motion, which practically renders any object to experience a weightless environment, thus the gravitational component pointing towards the center of the planet is practically canceled.
You might have seen images from the International Space Station of cosmonauts playing with water droplets, which had a rough spherical shape. Again, the surface tension of the water forces the liquid into an object with the smallest surface area possible. Each water molecule pulls towards the other with equal force in every direction, determining an elastic skin-like behavior of the surface.
The same process takes place with massive objects such as the stars, planets or centaurs; however, in this case, the surface tension is replaced by the extreme gravitational fields which also pull in every direction to create an object with minimal surface area.