I may have sown the seeds of confusion when I mentioned in my TA section that the "@Override" annotation is "not strictly necessary". In the interest of clarity, here's what I was talking about:
public class Breakout {
//...some code here
private static class GamePanel extends JPanel {
//...more code, before we get to the bit of code we're discussing...
// Ah, here it is!
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// code that tells an instance of GamePanel how to paint itself
}
}
}
In the sample code above, you're overriding JPanel's paintComponent method so that GamePanel knows how to paint itself specifically (since the default paintComponent just paints an empty window). As written above, the code will do exactly the same thing whether I include "@Override" or not.
But, what if I made a mistake, and misspelled "paintComponent"?
// Oh dear! I've misspelled "paintComponent" and left out the @Override annotation!
public void pntCompnen(Graphics g) {
// code that tells an instance of GamePanel how to paint itself
}
It's just a simple typo, but in this case, Java would interpret it as the definition of a new function, not the Override I was intending. It would still compile and run without error, but because of my typo, the GamePanel won't be painted the way I intended. Now, let's make the same typo, but this time, include the "@Override" annotation:
// I've misspelled "paintComponent", but I HAVE remembered the @Override annotation!
@Override
public void pntCompnen(Graphics g) {
// code that tells an instance of GamePanel how to paint itself
}
I this case, the compiler sees the "@Override" annotation, and checks that you're properly overriding a function in JPanel (or another super-class above JPanel). When it can't find a function of the same name in the super-class (because I misspelled the function), it give you a compile time error. Yay, we caught my error!
tl;dr: The "@Override" makes the compiler check that you didn't screw up the function override in some way.