Hi,
like you said, Java code needs to be compiled.
So, you can't simply copy&paste that code somewhere in Alfresco (like you do with normal Web Scripts), and expect results.
The part about declaring is similar too. Generally, this is something completely different in comparison to normal Web Scripts.
I suggest you get Eclipse, Alfresco source, and start from there.
Hopefully, you'll get a few more advices from more experienced people here.
Cheers,
Lista.