Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Polymorphism in java

@Override

The @Override annotation is a standard Java annotation that was first introduced in Java 1.51. It denotes that the child class method overrides the base class method. The @Override annotation is useful for two reasons: Compile-time Error: If the programmer makes a mistake while overriding, such as using the wrong method name or parameter types, you’ll get a compile-time error. This is because you are informing the compiler that you are overriding this method by using this annotation. If you don’t use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method). Improves Code’s Readability: It improves the code’s readability. If you change the signature of an overridden method, all sub-classes that override it will throw a compilation error, which will eventually lead to you changing the signature in the subclasses. Here’s an example of how you can use the @Override annotation:
@override basic syntax public class MyClass extends SomeClass { @Override public void someMethod() { // method implementation } }
In this example, the someMethod in MyClass overrides the someMethod in SomeClass. Here is an example to understand annotation behavior. It is not mandatory to use @override annotation but it is best practice to use.
@Override annotation example in java abstract class Vehicle { public abstract void method(); } class Car extends Vehicle { @Override public void method() { System.out.println("This is Car"); } } class Bike extends Vehicle { public void method() { System.out.println("This is Bike"); } } public class Main { public static void main(String[] args) { Car Carobj = new Car(); Carobj.method(); Bike Bikeobj = new Bike(); Bikeobj.method(); } }

Output

This is Car This is Bike
This annotation is considered a best practice for coding in Java because it helps to prevent errors and enhances the readability of the code.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ Polymorphism ★ Superclass ★ subclass

Tutorials