Interview question
What are annotations in Java and what are some commonly used built-in annotations? Java में annotations क्या हैं और commonly used built-in annotations क्या हैं?
Answer
Annotations are metadata attached to code (classes, methods, fields) that don't directly affect program logic but provide information used by the compiler, tools, or at runtime via reflection.
| Annotation | Purpose |
|---|---|
| @Override | Verifies a method actually overrides a parent method (compile-time check) |
| @Deprecated | Marks code as outdated, generates compiler warnings if used |
| @SuppressWarnings | Tells the compiler to ignore specific warnings |
| @FunctionalInterface | Enforces an interface has exactly one abstract method |
| @SafeVarargs | Suppresses unchecked warnings for varargs with generics |
class Animal {
public void makeSound() {
System.out.println('Some sound');
}
}
class Dog extends Animal {
@Override // catches typos - if method name doesn't match parent, compile error
public void makeSound() {
System.out.println('Bark');
}
}
class Utility {
@Deprecated
public static void oldMethod() {
System.out.println('This method is outdated');
}
@SuppressWarnings('unchecked')
public static void suppressExample() {
List rawList = new ArrayList();
List<String> list = rawList; // would normally warn, suppressed here
}
}
// Using a deprecated method triggers a compiler warning
Utility.oldMethod(); // warning: [deprecation] oldMethod() is deprecated
// @Override catching a real bug
class BadDog extends Animal {
// @Override
// public void makeSond() { // typo! Without @Override, this silently
// System.out.println('Bark'); // creates a NEW method instead of overriding
// }
}Annotations code (classes, methods, fields) से attached metadata हैं जो directly program logic को affect नहीं करते पर compiler, tools, या runtime पर reflection के ज़रिए इस्तेमाल होने वाली information देते हैं।
| Annotation | उद्देश्य |
|---|---|
| @Override | Method वाकई parent method override करता है, verify करता है |
| @Deprecated | Outdated code mark करता है |
| @SuppressWarnings | Specific warnings ignore करने को कहता है |
| @FunctionalInterface | एक abstract method enforce करता है |
class Animal {
public void makeSound() {
System.out.println('Some sound');
}
}
class Dog extends Animal {
@Override // typos पकड़ता है
public void makeSound() {
System.out.println('Bark');
}
}
class Utility {
@Deprecated
public static void oldMethod() {
System.out.println('यह method outdated है');
}
@SuppressWarnings('unchecked')
public static void suppressExample() {
List rawList = new ArrayList();
List<String> list = rawList;
}
}
Utility.oldMethod(); // deprecation warningWas this answer clear?