A police spokesman said, "Shortly after arriving at Heidingsfeld district of Wuerzburg, a man attacked passengers with an axe and a knife. Three people have been seriously injured and several others lightly injured."
He added: "The perpetrator was able to leave the train, police left in pursuit and as part of this pursuit, they shot the attacker and killed him."
Bavarian Interior Minister Joachim Herrmann said the attacker was a 17-year-old Afghan asylum seeker who had arrived in Germany as an unaccompanied minor and had been living with a foster family in Ochsenfurt, south of Wurzburg, for "a few months".
Herrmann told public broadcaster ARD that authorities were looking into media reports citing witnesses who said they had heard the attacker shout Allahu Akbar ("God Is Great") during the attack.
Eyewitness Thomas Velten, who went to see what had happened after the train stopped, told the Main Post newspaper that the carriage was "like a battlefield" with a large amount of blood.
The motive of the attack was not immediately clear.
About 1.2 million refugees are estimated to be living in Germany. Latest estimates by the European commission put the number of asylum seekers in Europe by the end of 2017 at around 3 million.
According to a study published in April by Germany’s Friedrich Ebert Foundation, around 154,000 Afghan citizens migrated to Germany in 2015, of whom 32,000 applied for asylum. More than 120,000 Afghan citizens remained in Germany without authorisation or had moved on to other countries, according to the study.
Image: German emergency services workers work in the area where a man with an axe attacked passengers on a train near the city of Wuerzburg, Germany early July 19. Photograph: Kai Pfaffenbach/Reuters
REVEALED: The faces behind the Dhaka terror attack
Terror ploughs into France once again; 10 kids among 84 killed
The ISIS threat is real, and not far away
France's brush with ISIS has lessons for India
Run over 'disbelievers' with cars: ISIS told supporters before Nice attack