Java Intermediate: Annotations

Once I was driving, but got pulled over by a state trooper. He saw the sticker on my windshield, stating that my car is due for its annual inspection soon. I told him I had an appointment scheduled for this weekend. He understood, letting me go on my way. This officer didn’t know the context of my situation and couldn’t know until told. This wasn’t wrong, he was just doing his job. Today we’re going to be talking about annotations which just help Java Virtual Machine (JVM) compilers do their jobs.

Java annotations are attached to classes, methods, or fields, represented with @ and represent metadata (data about data) for the compiler. Apply by placing the annotation at line above whatever you’re applying it to, like so:

class Parent {
	void speak() { System.out.println("I can talk!") }
}

class Toddler extends Parent {
	@Override
	void speak() { System.out.println("I can tawk!") }
}

In my earlier statement about my vehicle’s upcoming annual inspection, this is an example of giving context to the compiler that it otherwise wouldn’t have, displaying errors during compile time. Let’s look at a few:

  • @Override – the most common, assures that subclass method is overriding parent class method. In Java, this overrides existing behavior of a method, as seen above. Same method, different behavior in subclass.
  • @SuppressWarnings – is self-explanatory. Normally warnings are welcome unless they become annoying or inappropriate during compile time, such as an excessive number of warnings.
  • @Deprecated – marks method as deprecated so that compiler will print a warning about it. Good practice to use compiler for warning others what NOT to do for future versions.

These three annotations are applied to Java code use. Java annotations substitute the needs for XML or a marker (empty) interface. There are other annotations as well; users may even create their own Java annotations if necessary! To interact with the compiler and give it and others context in your next Java program, try using annotations.

Follow my original code on my GitHub profile!

Leave a comment

Design a site like this with WordPress.com
Get started