Energy Transformation in Flyback Transformers
and energy is going to be stored in the core

actually, in the magnetic field.
When the switch closes, the secondary diode will be reverse biased (remember the dots - winding polarities) and does not let the current flow.

But after opening the switch, how polarity changes?

Remember the basic inductor behavior: Inductors always generate an emf to counteract any change on the applied voltage. For example, if the applied voltage is suddenly removed then the inductor will generate a very high voltage with reversed polarity across its terminals.
Let's put this behavior in a flyback converter: When the switch opens, the primary inductor will not let the current stop suddenly and will generate a reversed and very high voltage across its terminals. So the voltage at the switch side of the inductor will be greater than the voltage at the supply side of the inductor. That's how the polarity changes.
The stored energy will be partly (or completely, hence the name DCM or CCM) transferred to the secondary. This will induce a voltage across the secondary winding.
Changing the polarities on the windings is the only thing that the flyback transformer can do because it has to transfer the stored energy. If the stored energy will not be transferred to the secondary then the core will never reset and will saturate eventually (Remember the B-H Loop).