• [email protected]

not annotated method is used as an override

What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

FavTutor

  • Don’t have an account Yet? Sign Up

Remember me Forgot your password?

  • Already have an Account? Sign In

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

By Signing up for Favtutor, you agree to our Terms of Service & Privacy Policy.

Overriding in Java (Methods, Uses, Examples)

  • Nov 16, 2023
  • 10 Minutes Read
  • Why Trust Us We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Nihal Mahansaria

Overriding in Java (Methods, Uses, Examples)

Method overriding serves as a foundation in object-oriented programming for achieving polymorphism, a fundamental principle that permits different classes to be treated as instances of the seme class via a common interface. Particularly, subclasses of method overriders are able to provide their own implementation of a method that was declared in the superclass.  In this article, we will learn the concept of Method overriding along with examples.

Overview of Method Overriding

Method overriding establishes a clear link between a superclass and it's subclasses. When a subclass inherits a method from its superclass, it can redefine the method to suit its specific needs. This enables the creation of a more specialized behavior without modifying the superclass, adhering to the open-closed principle of object-oriented design. In Java, method overriding is tightly connected to inheritance and is vital for achieving dynamic polymorphism.

Rules and Conditions for Method Overriding

Rules to Follow:

  • Method Signature Matching: The overriding method in the subclass must have the seme method signature as the overridden method in the superclass. This includes the method name, parameters, and return type.
  • Covariant Return Types: Java allows the return type of the overriding method to be a subtype of the overridden method. This is known as covariant return types.
  • Access Modifiers: The access modifier of the overriding method can't be more restrictive than the overridden method. For example, if the overridden method is public, the overriding method cannot be private.
  • Exception Handling: The overriding method can't throw checked exceptions broader than the ones thrown by the overridden method.

In this example, the Dog class adheres to the rules of method overriding by matching the signature of the makeSound method in the Animal class.

@Override Annotation

The @Override annotation is a valuable tool provided by Java to explicitly indicate that a method in a subclass is intended to override a method in its superclass. While not mandatory, using this annotation helps catch errors at compile-time if the annotated method does not correctly override a method in the superclass.

By adding @Override before the eat method in the Dog class, developers can ensure that they are correctly overriding the eat method from the Animal class.

Examples of Method Overriding

Let’s look at some examples of Method Overriding.

In this example, the Circle class provides a specific implementation of the draw method, tailored for drawing circles, which overrides the more general implementation in the Shape class.

Here, the Car class overrides the start method of the Vehicle class, specifying the behavior for starting a car.

Use of Super Keyword in Method Overriding

The super keyword in Java plays a crucial role in method overriding. It allows the subclass to explicitly call the overridden method in the superclass, providing a way to extend or modify the behavior defined in the superclass.

In this example, the super.makeSound() statement invokes the makeSound method from the Animal class before executing the Bark statement in the Dog class.

Covariant Return Types

Covariant return types, introduced in Java 5, allow a subclass to override a method with a return type that is a subtype of the return type in the superclass. This provides more flexibility and precision when designing class hierarchies.

Here, the Dog class overrides the reproduce method with a more specific return type, indicating the birth of a new dog.

Pitfalls and Common Mistakes

One common mistake in method overriding is forgetting to use the @Override annotation when intending to override a method. This omission can lead to unintentional method creation instead of overriding.

Adding @Override before the sing method in the Sparrow class would catch the error at compile-time, ensuring the method is intended for overriding.

What is Dynamic Method Dispatch?

Dynamic Method Dispatch is a critical concept in method overriding, facilitating the selection of the appropriate version of the overridden method at runtime based on the actual type of the object.

  

In this example, the makeSound method of the Dog class is called even though the reference is of type Animal, showcasing the power of dynamic method dispatch.

Best Practices for Method Overriding

  • Use @Override annotation: Always use the @Override annotation when intending to override a method. It helps catch errors at compile-time and ensures that the method is correctly overridden.
  • Follow naming conventions: Maintain consistency and meaningful method names to enhance code readability. This is especially crucial when working with large codebases or collaborating with other  developers.
  • Understand the purpose of the overridden method: Before overriding a method, thoroughly understand its purpose in the superclass. Ensure that the overridden method in the subclass server the seme purpose or behavior, adhering to the principle of least astonishment.

Use Cases and Real-world Examples

Java's java.util.ArrayList class provides a practical application of method overriding. The equals method is overridden to enable meaningful comparison of lists.

In this scenario, the overridden equals method in ArrayList ensures that the contents of the lists are compared, offering a more meaningful comparison for the specific context of lists.

Method overriding in Java is a powerful mechanism that promotes code reusability and flexibility. By understanding the rules, best practices, and nuances of method overriding, developers can create robust and maintainable object-oriented systems. From the fundamental principles of inheritance to the intricacies of dynamic method dispatch, method overriding empowers developers to craft sophisticated and extensible code. 

not annotated method is used as an override

FavTutor - 24x7 Live Coding Help from Expert Tutors!

not annotated method is used as an override

About The Author

not annotated method is used as an override

Nihal Mahansaria

More by favtutor blogs, biddecimal class in java (with examples).

not annotated method is used as an override

Getters and Setters in Java (with Examples)

not annotated method is used as an override

Enhanced For Loop Java (with Codes)

not annotated method is used as an override

Java @Override annotation examples

Some rules about @override annotation:.

  • The method does not override or implement a method declared in the supertype. Or:
  • The method is not an overriding version of a public method declared in the Object class. The Object’s pubic methods are: equals() , hashCode() and toString() . This is a special case regarding the interfaces in which an interface has public abstract members that correspond to the public members of Object class ( Java Language Specification, section 9.2 ).

Java @Override Annotation Examples:

  • Override a method from super class: Superclass: class Foo { public void doSomething(String thing, int times) { } } Subclass: class Bar extends Foo { @Override public void doSomething(String thing, int times) { // do something cooler } }
  • Implement a method from super interface: Super interface: interface Kool { void playCool(int x, int y); } Subclass: class Kooler implements Kool { @Override public void playCool(int x, int y) { } }
  • Override methods from the Object class: class Person { @Override public boolean equals(Object obj) { } @Override public int hashCode() { } @Override protected Person clone() { } }  
  • Overriding public methods of Object in an interface: This won’t compile because the clone() method is declared protected in the Object class: interface Kool { @Override public Object clone(); } But this will compile: interface Boom { @Override boolean equals(Object obj); }
  • Java @Deprecated annotation examples
  • Java @SuppressWarnings annotation examples

Other Recommended Tutorials:

  • 9 Rules about Constructors in Java
  • 12 Rules and Examples About Inheritance in Java
  • 12 Rules of Overriding in Java You Should Know
  • 10 Java Core Best Practices Every Java Programmer Should Know
  • Understand Interfaces in Java
  • Understand abstraction in Java
  • Understand encapsulation in Java
  • Understand inheritance in Java
  • Understand polymorphism in Java

About the Author:

not annotated method is used as an override

Add comment

   

Notify me of follow-up comments

Comments  

IMAGES

  1. not annotated method overrides @nonnullapi parameter

    not annotated method is used as an override

  2. Overriding in Java

    not annotated method is used as an override

  3. Overriding in Java Example Program

    not annotated method is used as an override

  4. not annotated method overrides @nonnullapi parameter

    not annotated method is used as an override

  5. Method Overriding in Java

    not annotated method is used as an override

  6. advantages of method overriding in java

    not annotated method is used as an override

VIDEO

  1. Boy vs Men vs Sigmas World Leaders #history #edit #shorts

  2. can not override static method

  3. Indian Air Force

  4. my first ever edit from 500 BC 👍🏻

  5. Final, Abstract and Normal Method in Java

  6. Can we override a method which doesn't exists in parent class (Core Java Interview Question #110)

COMMENTS

  1. Java @Override Annotation

    2. @Override Annotation. In a subclass, we can override or overload instance methods. Overriding indicates that the subclass is replacing inherited behavior. Overloading is when a subclass is adding new behavior. Sometimes, we’ll overload by accident when we actually intended to override. It’s easy to make this mistake in Java:

  2. Overriding in Java (Methods, Uses, Examples)

    The @Override annotation is a valuable tool provided by Java to explicitly indicate that a method in a subclass is intended to override a method in its superclass. While not mandatory, using this annotation helps catch errors at compile-time if the annotated method does not correctly override a method in the superclass.

  3. Java @Override annotation examples

    When a method is marked with the @Override annotation, the compiler will perform a check to ensure that the method does indeed override or implement a method in super class or super interface. This helps in preventing unintentional errors such as misspelled method name, wrongly-typed parameters or anything that does not obey overriding rules.