The createQueryDef() method in Workspace returns an IQueryDef, of which IQueryDef2 is a subinterface. What you want is an actual QueryDef.

"IQueryDef2 query = (IQueryDef2) fw.createQueryDef(); "

What you are doing here is trying to assign a cast of IQueryDef as IQueryDef2 to an IQueryDef2 type. fw.createQueryDef() already returns an IQueryDef type and you're trying to cast that as an IQueryDef2.