At around the age of 2.5, many littles have the brain development that allows them to BEGIN comprehending abstract ideas like sharing. It's still a long, slow process to internalize the understanding that sharing actually enhances everyone's experience, even the child's who lets go of some material goodie. And there are personality characteristics, including assertiveness, acquisitiveness, and fearfullness, that are considerably stronger in some people/children than others, which can make this a much harder rule of life for many of us to learn. (Look at all the adults in the world who still believe "It was given to me, or I earned it, so it's mine alone.)
At younger ages, it is possible to teach many kids sharing as a game. As long as there are positive strokes or rewards for sharing that are at least as important to the child as taking/keeping some desired object, they can happily participate. It can take some pretty creative parenting to help a child "enjoy" sharing, but it can be done.
And of course, many (not all) young children can be forced, intimidated, or punished out of certain behaviors. This is the "traditional" way to approach the problem, and it is effective, up to a point. But it can also keep the "correct response" externalized, and cause some more spirited or more timid children to react in ways that are not at all what parents hope for. Some children never learn to do good for good's sake, but will behave only as long as some powerful authority figure might be watching them.
We all hope our kids will internalize good social behavior, and for the past couple of decades, much research is being done to learn what approaches will work best for most children, or for children with certain personality types. One thing that is generally recognized is that all behaviors, by adult or child, are strategies to meet some perceived need, and most needs are valid.
But for very young children, their strategies generally need a lot of growing up. What worked best for my daughter, grandson, and many of the other toddlers I've interacted with is making sharing a low-pressure game, trading items back and forth with an adult, with a lot of laughter and praise. Positive strokes work before impulse control becomes available.