Welcome to the Ranch!
Well, the answer's simple.
Java is an object-oriented language, and in a class is the only place it
allows you to write code. So you don't need an example to demonstrate that.
If you mean, "why is it designed that way", that's a huge question that we're not going to be able to effectively answer here. I'd suggest reading a tutorial on object-oriented programming to get an idea of how it works.
If you've got some more specific questions we might be able to help you.